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:
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:
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.
>>> 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!
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:
In this assignment, you will implement an out-of-core
version of the group by aggregate (aggregation by key)
seen in lecture. You will have a set memory limit and
you will have to count the number of times a string shows
up in an iterator. Your program should work for any limit
> 20.
## Getting Started
First, pull the most recent changes from the cmsc13600-public repository:
```
$ git pull
```
Then, copy the `hw5` folder to your submission repository. Change directories to enter your submission repository. Your code will go into `countD.py` this is the only file that you will modify. Finally, add `countD.py` using `git add`:
```
$ git add countD.py
$ git commit -m'initialized homework'
```
Now, you will need to fetch the data used in this assignment. Download title.csv put it in the hw5 folder:
DO NOT ADD title.csv to the git repo! After downloading the
dataset, there is a python module provided for you called `core.py`, which reads the dataset. This module loads the data in as
an iterator in two functions `imdb_years()` and `imdb_title_words()`:
```
>> for i in imdb_years():
... print(i)
1992
1986
<so on>
```
Play around with both `imdb_years()` and `imdb_title_words()` to get a feel for how the data works.
## MemoryLimitedHashMap
In this project, the main data structure is the `MemoryLimitedHashMap`. This is a hash map that has an explicit limit on the number of keys it can store. To create one of these data structure, you can import it from core module:
```
from core import *
#create a memory limited hash map
m = MemoryLimitedHashMap()
```
To find out what the limit of this hash map is, you can:
```
print("The max size of m is: ", m.limit)
```
The data structure can be constructed with an explicit limit (the default is 1000), e.g., `MemoryLimitedHashMap(limit=10)`.
Adding data to this hash map is like you've probably seen before in a data structure class. There is a `put` function that takes in a key and assigns that key a value:
```
# put some keys
m.put('a', 1)
m.put('b', 45)
print("The size of m is: ", m.size())
```
You can fetch the data using the `get` function and `keys` function:
```
# get keys
for k in m.keys():
print("The value at key=", k, 'is', m.get(k))
# You can test to see if a key exists
print('Does m contain a?', m.contains('a'))
print('Does m contain c?', m.contains('c'))
```
When a key does not exist in the data structure the `get` function will raise an error:
```
#This gives an error:
m.get('c')
```
Similarly, if you assign too many unique keys (more than the limit) you will get an error:
```
for i in range(0,1001):
m.put(str(i), i)
```
The `MemoryLimitedHashMap` allows you to manage this limited storage with a `flush` function that allows you to persist a key and its assignment to disk. When you flush a key it removes it from the data structure and decrements the limit. Flush takes a key as a parameter.
```
m.flushKey('a')
print("The size of m is: ", m.size())
```
Note that the disk is not intelligent! If you flush a key multiple times it simply appends the flushed value to a file on disk:
```
m.flushKey('a')
<some work...>
m.flushKey('a')
```
Once a key has been flushed it can be read back using the `load` function (which takes a key as a parameter). This loads back *all* of the flushed values:
```
#You can also load values from disk
for k,v in m.load('a'):
print(k,v)
```
If you try to load a key that has not been flushed, you will get an error:
```
#Error!!
for k,v in m.load('d'):
print(k,v)
```
If you want multiple flushes of the same key to be differentiated, you can set a *subkey*:
```
#first flush
m.flushKey('a', '0')
<some work...>
#second flush
m.flushKey('a', '1')
```
The `load` function allows you to selectively pull