README.md 21.6 KB
Newer Older
Sanjay Krishnan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
# Extract-Transform-Load

*Due 5/18/20 11:59 PM*
Extract, transform, load (ETL) is the general procedure of copying data from one or more sources into a destination system which represents the data differently from the source(s). In this project, you will write some of the core primitives in an ETL system. 

## Getting Started
First, pull the most recent changes from the cmsc13600-public repository:
```
$ git pull
```
Then, copy the `hw4` folder to your submission repository. Change directories to enter your submission repository. Your code will go into the `etl.py`  and `etl_programs.py` files. You can the files to the repository using `git add`:
```
$ git add *.py
$ git commit -m'initialized homework'
```
You will additionally have to install the Pandas library to do this assignment:
```
$ pip3 install pandas
```

Feel free to skip this section if you already know how Pandas works. Pandas is a data analysis toolkit for Python that makes it easy to work with tabular data. We organize our tutorial of this library around an exploration of data from the 2015 New York City Street Tree Survey, which is freely available from the New York City open data portal (https://data.cityofnewyork.us). This survey was performed by the New York City Department of Parks and Recreation with help from more than 2000 volunteers. The goal of the survey is to catalog the trees planted on the City right-of-way, typically the space between the sidewalk and the curb, in the five boroughs of New York. The survey data is stored in a CSV file that has 683,789 lines, one per street tree. (Hereafter we will refer to trees rather than street trees for simplicity.) The census takers record many different attributes for each tree, such as the common name of the species, the location of the tree, etc. Of these values, we will use the following:

* boroname: the name of the borough in which the tree resides;
*health: an estimate of the health of the tree: one of good, fair, or poor;
* latitude and longitude : the location of the tree using geographical coordinates;
* spc_common: the common, as opposed to Latin, name of the species;
status: the status of the tree: one of alive, dead, or stump;
* tree_id: a unique identifier

Some fields are not populated for some trees. For example, the health field is not populated for dead trees and stumps and the species field (spc_common) is not populated for stumps and most dead trees. 

To use pandas, you can simply import it as follows:
```
>>> import pandas as pd
```

DataFrames are the the main data structure in Pandas. The library function pd.read_csv takes the name of a CSV file and loads it into a data frame. Let’s use this function to load the tree data from a file named 2015StreetTreesCensus_TREES.csv:
```
>>> trees = pd.read_csv("2015StreetTreesCensus_TREES.csv")
```
The variable trees now refers to a Pandas DataFrame. Let’s start by looking at some of the actual data. You can similarly create a DataFrame from lists:
```
>>> df = pd.DataFrame([['Bob', 'Stewart'],
                    ['Anna', 'Davis'],
                    ['Jerry', 'Dole'],
                    ['John', 'Marsh']],
                   columns=['first_name', 'last_name'])
```
We’ll explain the various ways to access data in detail later. For now, just keep in mind that the columns have names (for example, “Latitude”, “longitude”, “spc_common”, etc) and leverage the intuition you’ve built up about indexing in other data structures.

Here, for example, are a few columns from the first ten rows of the dataset:
```
>>> trees10 = trees[:10]
>>> trees10[["Latitude", "longitude", "spc_common", "health", "boroname"]]
    Latitude  longitude        spc_common health       boroname
0  40.723092 -73.844215         red maple   Fair         Queens
1  40.794111 -73.818679           pin oak   Fair         Queens
2  40.717581 -73.936608       honeylocust   Good       Brooklyn
3  40.713537 -73.934456       honeylocust   Good       Brooklyn
4  40.666778 -73.975979   American linden   Good       Brooklyn
5  40.770046 -73.984950       honeylocust   Good      Manhattan
6  40.770210 -73.985338       honeylocust   Good      Manhattan
7  40.762724 -73.987297   American linden   Good      Manhattan
8  40.596579 -74.076255       honeylocust   Good  Staten Island
9  40.586357 -73.969744  London planetree   Fair       Brooklyn
```

Notice that the result looks very much like a table in which both the columns and the rows are labelled. In this case, the column labels came from the first row in the file and the rows are simply numbered starting at zero.

Here’s the full first row of the dataset with all 41 attributes:
```
>>> trees.iloc[0]
created_at                                       08/27/2015
tree_id                                              180683
block_id                                             348711
the_geom      POINT (-73.84421521958048 40.723091773924274)
tree_dbh                                                  3
stump_diam                                                0
curb_loc                                             OnCurb
status                                                Alive
health                                                 Fair
spc_latin                                       Acer rubrum
spc_common                                        red maple
steward                                                None
guards                                                 None
sidewalk                                           NoDamage
user_type                                  TreesCount Staff
problems                                               None
root_stone                                               No
root_grate                                               No
root_other                                               No
trnk_wire                                                No
trnk_light                                               No
trnk_other                                               No
brnch_ligh                                               No
brnch_shoe                                               No
brnch_othe                                               No
address                                   108-005 70 AVENUE
zipcode                                               11375
zip_city                                       Forest Hills
cb_num                                                  406
borocode                                                  4
boroname                                             Queens
cncldist                                                 29
st_assem                                                 28
st_senate                                                16
nta                                                    QN17
nta_name                                       Forest Hills
boro_ct                                             4073900
state                                              New York
Latitude                                            40.7231
longitude                                          -73.8442
x_sp                                            1.02743e+06
y_sp                                                 202757
Name: 0, dtype: object
```

and here are a few specific values from that row:

```
>>> first_row = trees.iloc[0]
>>> first_row["Latitude"]
40.72309177
>>> first_row["longitude"]
-73.84421522
>>> first_row["boroname"]
'Queens'
```

Notice that the latitude and longitude values are floats, while the borough name is a string. Conveniently, read_csv analyzes each column and if possible, identifies the appropriate type for the data stored in the column. If this analysis cannot determine a more specific type, the data will be represented using strings.

We can also extract data for a specific column:

```
>>> trees10["boroname"]
0           Queens
1           Queens
2         Brooklyn
3         Brooklyn
4         Brooklyn
5        Manhattan
6        Manhattan
7        Manhattan
8    Staten Island
9         Brooklyn
Name: boroname, dtype: object
```

and we can easily do useful things with the result, like count the number of times each unique value occurs:
```
>>> trees10["boroname"].value_counts()
Brooklyn         4
Manhattan        3
Queens           2
Staten Island    1
Name: boroname, dtype: int64
```
Now that you have a some feel for the data, we’ll move on to discussing some useful attributes and methods provided by data frames. The shape attribute yields the number of rows and columns in the data frame:

```
>>> trees.shape
(683788, 42)
```
The data frame has fewer rows (683,788) than lines in the file (683,789), because the header row is used to construct the column labels and does not appear as a regular row in the data frame. To access a row using the row number, that is, its position in the data frame, we use iloc operator and square brackets:

```
>>> trees.iloc[3]
created_at                                       08/27/2015
block_id                                             348711
the_geom      POINT (-73.84421521958048 40.723091773924274)
tree_dbh                                                  3
stump_diam                                                0
curb_loc                                             OnCurb
status                                                Alive
health                                                 Fair
spc_latin                                       Acer rubrum
spc_common                                        red maple
steward                                                None
guards                                                 None
sidewalk                                           NoDamage
user_type                                  TreesCount Staff
problems                                               None
root_stone                                               No
root_grate                                               No
root_other                                               No
trnk_wire                                                No
trnk_light                                               No
trnk_other                                               No
brnch_ligh                                               No
brnch_shoe                                               No
brnch_othe                                               No
address                                   108-005 70 AVENUE
zipcode                                               11375
zip_city                                       Forest Hills
cb_num                                                  406
borocode                                                  4
boroname                                             Queens
cncldist                                                 29
st_assem                                                 28
st_senate                                                16
nta                                                    QN17
nta_name                                       Forest Hills
boro_ct                                             4073900
state                                              New York
Latitude                                            40.7231
longitude                                          -73.8442
x_sp                                            1.02743e+06
y_sp                                                 202757
Name: 180683, dtype: object
```

In both cases the result of evaluating the expression has type Pandas Series:
We can extract the values in a specific column using square brackets with the column name as the index:

```
>>> trees10["spc_common"]
tree_id
180683           red maple
200540             pin oak
204026         honeylocust
204337         honeylocust
189565     American linden
190422         honeylocust
190426         honeylocust
208649     American linden
209610         honeylocust
192755    London planetree
Name: spc_common, dtype: object
```

We can also use dot notation to access a column, if the corresponding label conforms to the rules for Python identifiers and does not conflict with the name of a DataFrame attribute or method:

```
>>> trees10.spc_common
tree_id
180683           red maple
200540             pin oak
204026         honeylocust
204337         honeylocust
189565     American linden
190422         honeylocust
190426         honeylocust
208649     American linden
209610         honeylocust
192755    London planetree
Name: spc_common, dtype: object
```

The tree dataset has many columns, most of which we will not be using to answer the questions posed at the beginning of the chapter. As we saw above, we can extract the desired columns using a list as the index:

```
>>> cols_to_keep = ['spc_common', 'status', 'health', 'boroname', 'Latitude', 'longitude']
>>> trees_narrow = trees[cols_to_keep]
>>> trees_narrow.shape
(683788, 6)
```

This new data frame has the same number of rows and the same index as the original data frame, but only six columns instead of the original 41.

If we know in advance that we will be using only a subset of the columns, we can specify the names of the columns of interest to pd.read_csv and get the slimmer data frame to start. Here’s a function that uses this approach to construct the desired data frame:

```
>>> def get_tree_data(filename):
...     '''
...     Read slim version of the tree data and clean up the labels.
... 
...     Inputs:
...         filename: name of the file with the tree data
... 
...     Returns: DataFrame
...     '''
...     cols_to_keep = ['tree_id', 'spc_common', 'status', 'health', 'boroname',
...                     'Latitude', 'longitude']
...     trees = pd.read_csv(filename, index_col="tree_id",
...                         usecols=cols_to_keep)
...     trees.rename(columns={"Latitude":"latitude"}, inplace=True)
...     return trees
... 
... 
>>> trees = get_tree_data("2015StreetTreesCensus_TREES.csv")
```

A few things to notice about this function: first, the index column, tree_id, needs to be included in the value passed with the usecols parameter. Second, we used the rename method to fix a quirk with the tree data: “Latitude” is the only column name that starts with a capital letter. We fixed this problem by supplying a dictionary that maps the old name of a label to a new name using the columns parameter. Finally, by default, rename constructs a new dataframe. Calling it with the inplace parameter set to True, causes frame updated in place, instead. 

We encourage you to read the Pandas API before you do this homework, most of the functions that you will implement are trivial if you have the right Pandas library routine!
https://pandas.pydata.org/pandas-docs/stable/reference/index.html

## Implementing ETL Functions
The ETL class defines basic language primitives for manipulating Pandas
DataFrames. It takes a DataFrame in and outputs a transformed DataFrame. You will implement several of the routines to perform these transformations.

Here is how we intend the `ETL` class to be used. You can create DataFrame and create an ETL class that takes the DataFrame as input.

```
>> df1 = pd.DataFrame([['Bob', 'Stewart'],
                       ['Anna', 'Davis'],
                       ['Jerry', 'Dole'],
                       ['John', 'Marsh']],
                      columns=["first_name", "last_name"])
>> etl = ETL(df1)
```

For example, the add() function creates a new column with a specified value. We might want to add a new colum to represent ages:
```
>> etl.add("age", 0)
>> etl.df
  first_name last_name  age
0        Bob   Stewart    0
1       Anna     Davis    0
2      Jerry      Dole    0
3       John     Marsh    0
```

### Drop and Copy
As a warm-up, the first functions that you will write are `drop(colname)` which drops a column from the dataset with a specific column name.
```
>> etl.drop(colname="first_name")
>> etl.df
  last_name
0   Stewart
1     Davis
2      Dole
3     Marsh
```
and `copy(colname, new_colname)` which duplicates a column and saves it to the new name:
```
>> etl.copy(colname="first_name", new_colname="first_name2")
>> etl.df
  first_name last_name first_name2
0        Bob   Stewart         Bob
1       Anna     Davis        Anna
2      Jerry      Dole       Jerry
3       John     Marsh        John
```

### Split/Merge
Next, you will write a `split(colname, new_colname, splitter)` function. This function takes an input dataframe and splits all values in colname on a delimiter. It puts the substring before the delimiter in colname, and the substring after the delimiter in a new column. For example,
```
>>> df1 = pd.DataFrame([['Bob-Stewart'],
                    ['Anna-Davis'],
                    ['Jerry-Dole'],
                    ['John']],
                   columns=["name"])
>>> etl = ETL(df1)
>> etl.split("name", "last_name","-")
>> etl.df
    name last_name
0    Bob   Stewart
1   Anna     Davis
2  Jerry      Dole
3   John          
```
When a value does not contain the delimiter new_colname is an empty string. The `merge` function does the opposite of `split`. It takes `merge(col1, col2, splitter)` replaces col1
with the values of col1 and col2 concatenated and seperated by the delimiter. If the value in either col1 or col2 is an empty string, then the delimiter is ignored:
```
>> etl.df
    name last_name
0    Bob   Stewart
1   Anna     Davis
2  Jerry      Dole
3   John 
>> pw1.merge("name", "last_name","-")
          name last_name
0  Bob-Stewart   Stewart
1   Anna-Davis     Davis
2   Jerry-Dole      Dole
3         John    
```
### Format
Next, you will write a `format` function that transforms values in a specified column. Format applies an input function to every value in a column. For example,
```
df1 = pd.DataFrame([['Bob-Stewart'],
                    ['Anna-Davis'],
                    ['Jerry-Dole'],
                    ['John']],
                   columns=["name"])
etl = ETL(df1)
etl.format("name", lambda x: x.replace("-",","))
>> etl.df
          name
0  Bob,Stewart
1   Anna,Davis
2   Jerry,Dole
3         John
```

### Divide
Divide conditionally divides a column, sending values that satisfy the condition into one of two columns. For example, consider the data frame below that has names delimited by two different delimiters. Divide can be used to separate these: 
```
df1 = pd.DataFrame([['Bob-Stewart'],
                    ['Anna-Davis'],
                    ['Jerry-Dole'],
                    ['John,Smith']],
                   columns=["name"])
etl = ETL(df1)
etl.divide("name", "dash", "comma", lambda x: '-' in x)
>> etl.df
          name         dash       comma
0  Bob-Stewart  Bob-Stewart            
1   Anna-Davis   Anna-Davis            
2   Jerry-Dole   Jerry-Dole            
3   John,Smith               John,Smith
```

##ETL Programs
Now, you will use the functions that you wrote to write ETL programs. The remainder of this homework must be completed using a sequence of functions from the ETL class. Your code goes into `etl_programs.py`. As an example, suppose we are given the data:
```
df1 = pd.DataFrame([['Bob-Stewart'],
                    ['Anna-Davis'],
                    ['Jerry-Dole'],
                    ['John,Smith']],
                   columns=["name"])
```
Some of the names are delimited by dashes and some by commas in a single column `name`. We want to to transform this dataframe to have two columns `first_name` and `last_name` with the appropriate names extracted from the dataframe. We could do the following:
```
>> pw1 = ETL(df1)
>> pw1.divide("name", "dash", "comma", lambda x: '-' in x) #divide on a dash
>> pw1.split("dash", "last_name_dash", "-") #split the dash column
>> pw1.split("comma", "last_name_comma", ",") #split the comma column
>> pw1.add("last_name", "")
>> pw1.add("first_name", "")
>> pw1.merge("first_name", "dash", "") #add the first names
>> pw1.merge("first_name", "comma", "")
>> pw1.merge("last_name", "last_name_dash", "") #add the lastnames
>> pw1.merge("last_name", "last_name_comma", "")
>> pw1.drop("name") #drop uncessary columns
>> pw1.drop("dash")
>> pw1.drop("comma")
>> pw1.drop("last_name_dash")
>> pw1.drop("last_name_comma")
>> pw1.df
  last_name first_name
0   Stewart        Bob
1     Davis       Anna
2      Dole      Jerry
3     Smith       John
```

The following functions are case insensitive.

### phone
You are given an input dataframe as follows:
```
df = pd.DataFrame([['(408)996-758'],
                      ['+1 667 798 0304'],
                      ['(774)998-758'],
                      ['+1 442 030 9595']],
                      columns=["phoneno"])
```
Write an ETL program that results in a dataframe with two columns: area_code, 
phone_number. area_code must be formated as a number with only digits (no parens) and the phone number must be of the form xxx-xxxx.

### date
You are given an input dataframe as follows:
```
 df = pd.DataFrame([['03/2/1990'],
                      ['2/14/1964'],
                      ['1990-04-30'],
                      ['7/9/2012'],
                      ['1989-09-13'],
                      ['1994-08-21'],
                      ['1996-11-30'],
                      ['2004-12-23'],
                      ['4/21/2016']]
                      columns=["date"])
```
Write an ETL program that results in a dataframe with three columns: day, month, year. The day must be in two-digit format i.e, 01, 08. The month must be the full month name, e.g., "May". The year must be in YYYY format.

### name
You are given an input dataframe as follows:
```
df = pd.DataFrame([['Such,Bob', ''],
                    ['Ann', 'Davis'],
                    ['Dole,Jerry', ''],
                    ['Joan', 'Song']],
                     columns=["first_name", "last_name"])
```
Some of the names are incorrectly formated where the "first_name" is actually the person's (last name,first name) Write an ETL program that correctly formats names
into first_name and last_name, so all the cells are appropriately filled.

## Submission
After you finish the assignment you can submit your code with:
```
$ git push
```