Commit 0d30ba50 by Sanjay Krishnan

Updated all

parent d457b468
# Extract-Transform-Load
*Extra Credit Assignment*
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
```
# Extract-Transform-Load # Out-of-Core Group By Aggregate
*Extra Credit Assignment* *Due Friday May 21, 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. 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
greater than 20.
## Getting Started ## Getting Started
First, pull the most recent changes from the cmsc13600-public repository: First, pull the most recent changes from the cmsc13600-public repository:
``` ```
$ git pull $ 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`: 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 *.py $ git add countD.py
$ git commit -m'initialized homework' $ 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; Now, you will need to fetch the data used in this assignment. Download title.csv put it in the hw5 folder:
*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. https://www.dropbox.com/s/zl7yt8cl0lvajxg/title.csv?dl=0
To use pandas, you can simply import it as follows: 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()`:
``` ```
>>> import pandas as pd >> 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.
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: ## 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:
``` ```
>>> trees = pd.read_csv("2015StreetTreesCensus_TREES.csv") from core import *
#create a memory limited hash map
m = MemoryLimitedHashMap()
``` ```
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: To find out what the limit of this hash map is, you can:
``` ```
>>> df = pd.DataFrame([['Bob', 'Stewart'], print("The max size of m is: ", m.limit)
['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. 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:
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
``` ```
# put some keys
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. m.put('a', 1)
m.put('b', 45)
Here’s the full first row of the dataset with all 41 attributes: print("The size of m is: ", m.size())
```
>>> 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
``` ```
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))
and here are a few specific values from that row: # 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'))
``` ```
>>> first_row = trees.iloc[0] When a key does not exist in the data structure the `get` function will raise an error:
>>> first_row["Latitude"]
40.72309177
>>> first_row["longitude"]
-73.84421522
>>> first_row["boroname"]
'Queens'
``` ```
#This gives an error:
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. m.get('c')
We can also extract data for a specific column:
``` ```
>>> trees10["boroname"] Similarly, if you assign too many unique keys (more than the limit) you will get an error:
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
``` ```
for i in range(0,1001):
and we can easily do useful things with the result, like count the number of times each unique value occurs: m.put(str(i), i)
``` ```
>>> trees10["boroname"].value_counts() 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.
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: m.flushKey('a')
print("The size of m is: ", m.size())
``` ```
>>> trees.shape 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:
(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: m.flushKey('a')
<some work...>
m.flushKey('a')
``` ```
>>> trees.iloc[3] 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:
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
``` ```
#You can also load values from disk
In both cases the result of evaluating the expression has type Pandas Series: for k,v in m.load('a'):
We can extract the values in a specific column using square brackets with the column name as the index: print(k,v)
``` ```
>>> trees10["spc_common"] If you try to load a key that has not been flushed, you will get an error:
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
``` ```
#Error!!
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: for k,v in m.load('d'):
print(k,v)
``` ```
>>> trees10.spc_common
tree_id If you want multiple flushes of the same key to be differentiated, you can set a *subkey*:
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
``` ```
#first flush
m.flushKey('a', '0')
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: <some work...>
#second flush
m.flushKey('a', '1')
``` ```
>>> cols_to_keep = ['spc_common', 'status', 'health', 'boroname', 'Latitude', 'longitude'] The `load` function allows you to selectively pull
>>> trees_narrow = trees[cols_to_keep] certain subkeys:
>>> trees_narrow.shape ```
(683788, 6) # pull only the first flush
m.load('a', '0')
``` ```
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. We can similarly iterate over all of the flushed data (which optionally takes a subkey as well!):
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): for k,v in m.loadAll():
... ''' print(k,v)
... 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")
``` ```
It also takes in an optional parameter that includes the in memory keys as well:
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'], for k,v in m.loadAll(subkey='myskey', inMemory=True):
['Anna', 'Davis'], print(k,v)
['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: Since there are some keys in memory and some flushed to disk there are two commands to iterate over keys.
``` ```
>> etl.add("age", 0) m.keys() #returns all keys that are in memory
>> etl.df
first_name last_name age
0 Bob Stewart 0
1 Anna Davis 0
2 Jerry Dole 0
3 John Marsh 0
``` ```
There is also a way to iterate over all of the flushed keys (will strip out any subkeys):
### 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
``` ```
m.flushed() #return keys that are flushed.
### 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 ## Count Per Group
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: In this assignment, you will implement an out-of-core count operator which for all distinct strings in an iterator returns
``` the number of times it appears (in no particular order).
df1 = pd.DataFrame([['Bob-Stewart'], For example,
['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
``` ```
In: "the", "cow", "jumped", "over", "the", "moon"
##ETL Programs Out: ("the",2), ("cow",1), ("jumped",1), ("over",1), ("moon",1)
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
``` ```
Or,
The following functions are case insensitive.
### phone
You are given an input dataframe as follows:
``` ```
df = pd.DataFrame([['(408)996-758'], In: "a", "b", "b", "a", "c"
['+1 667 798 0304'], Out: ("c",1),("b",2), ("a", 2)
['(774)998-758'],
['+1 442 030 9595']],
columns=["phoneno"])
``` ```
Write an ETL program that results in a dataframe with two columns: area_code, The catch is that you CANNOT use a list, dictionary, or set from
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. Python. We provide a general purpose data structure called a MemoryLimitedHashMap (see ooc.py). You must maintain the iterator
state using this data structure.
### date The class that you will implement is called Count (in countD.py).
You are given an input dataframe as follows: The constructor is written for you, and ittakes in an input iterator and a MemoryLimitedHashMap. You will use these objects
``` in your implementation. You will have to implement `__next__` and `__iter__`. Any solution using a list, dictionary, or set inside `Count` will recieve 0 points.
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 The hint is to do this in multiple passes and use a subkey to track keys flushed between different passes.
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 ## Testing and Submission
After you finish the assignment you can submit your code with: We have provided a series of basic tests in `auto_grader.py`, these tests are incomplete and are not meant to comprehensively grade your assignment. There is a file `years.json` with an expected output. After you finish the assignment you can submit your code with:
``` ```
$ git push $ git push
``` ```
# Out-of-Core Group By Aggregate
*Due Friday May 21, 11:59 pm*
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
greater than 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:
https://www.dropbox.com/s/zl7yt8cl0lvajxg/title.csv?dl=0
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
certain subkeys:
```
# pull only the first flush
m.load('a', '0')
```
We can similarly iterate over all of the flushed data (which optionally takes a subkey as well!):
```
for k,v in m.loadAll():
print(k,v)
```
It also takes in an optional parameter that includes the in memory keys as well:
```
for k,v in m.loadAll(subkey='myskey', inMemory=True):
print(k,v)
```
Since there are some keys in memory and some flushed to disk there are two commands to iterate over keys.
```
m.keys() #returns all keys that are in memory
```
There is also a way to iterate over all of the flushed keys (will strip out any subkeys):
```
m.flushed() #return keys that are flushed.
```
## Count Per Group
In this assignment, you will implement an out-of-core count operator which for all distinct strings in an iterator returns
the number of times it appears (in no particular order).
For example,
```
In: "the", "cow", "jumped", "over", "the", "moon"
Out: ("the",2), ("cow",1), ("jumped",1), ("over",1), ("moon",1)
```
Or,
```
In: "a", "b", "b", "a", "c"
Out: ("c",1),("b",2), ("a", 2)
```
The catch is that you CANNOT use a list, dictionary, or set from
Python. We provide a general purpose data structure called a MemoryLimitedHashMap (see ooc.py). You must maintain the iterator
state using this data structure.
The class that you will implement is called Count (in countD.py).
The constructor is written for you, and ittakes in an input iterator and a MemoryLimitedHashMap. You will use these objects
in your implementation. You will have to implement `__next__` and `__iter__`. Any solution using a list, dictionary, or set inside `Count` will recieve 0 points.
The hint is to do this in multiple passes and use a subkey to track keys flushed between different passes.
## Testing and Submission
We have provided a series of basic tests in `auto_grader.py`, these tests are incomplete and are not meant to comprehensively grade your assignment. There is a file `years.json` with an expected output. After you finish the assignment you can submit your code with:
```
$ git push
```
...@@ -18,21 +18,21 @@ ...@@ -18,21 +18,21 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 3, "execution_count": 63,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"{'a': 1, 'b': 2, 'c': [1, 2, 3]}\n" "{'a': 1, 'b': 5, 'c': [1, 2, 3]}\n"
] ]
} }
], ],
"source": [ "source": [
"my_dict = {}\n", "my_dict = {} #dictionary\n",
"my_dict['a'] = 1\n", "my_dict['a'] = 1\n",
"my_dict['b'] = 2\n", "my_dict['b'] = 5\n",
"my_dict['c'] = [1,2,3]\n", "my_dict['c'] = [1,2,3]\n",
"\n", "\n",
"print(my_dict)" "print(my_dict)"
...@@ -47,7 +47,7 @@ ...@@ -47,7 +47,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 6, "execution_count": 64,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
...@@ -64,14 +64,14 @@ ...@@ -64,14 +64,14 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 8, "execution_count": 65,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"{'a': 1, 'b': 2, 'c': [1, 2, 3]}\n" "{'a': 1, 'b': 5, 'c': [1, 2, 3]}\n"
] ]
} }
], ],
...@@ -99,14 +99,14 @@ ...@@ -99,14 +99,14 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 13, "execution_count": 66,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"{\"a\": 1, \"b\": 2, \"c\": [1, 2, 3]}\n" "{\"a\": 1, \"b\": 5, \"c\": [1, 2, 3]}\n"
] ]
} }
], ],
...@@ -120,14 +120,14 @@ ...@@ -120,14 +120,14 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 14, "execution_count": 67,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
"name": "stdout", "name": "stdout",
"output_type": "stream", "output_type": "stream",
"text": [ "text": [
"{'a': 1, 'b': 2, 'c': [1, 2, 3]}\n" "{'a': 1, 'b': 5, 'c': [1, 2, 3]}\n"
] ]
} }
], ],
...@@ -220,7 +220,7 @@ ...@@ -220,7 +220,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 34, "execution_count": 68,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -380,7 +380,7 @@ ...@@ -380,7 +380,7 @@
"source": [ "source": [
"def get_skeleton(struct, prefix=''):\n", "def get_skeleton(struct, prefix=''):\n",
" \n", " \n",
" #base case\n", " #base case (\"atomic data type\")\n",
" if not type(struct) is dict:\n", " if not type(struct) is dict:\n",
" return\n", " return\n",
" \n", " \n",
...@@ -409,11 +409,11 @@ ...@@ -409,11 +409,11 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 24, "execution_count": 73,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"scores = [{'name': 'Jared', 'score': 77}, {'name': 'Sylvie', 'score': 82}, {'name': 'Bud', 'score': 66} ]\n", "#scores = [{'name': 'Jared', 'score': 77}, {'name': 'Sylvie', 'score': 82}, {'name': 'Bud', 'score': 66} ]\n",
"\n", "\n",
"json.dump(scores, open('tests.json','w'))" "json.dump(scores, open('tests.json','w'))"
] ]
...@@ -427,14 +427,18 @@ ...@@ -427,14 +427,18 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 17, "execution_count": 74,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
"name": "stdout", "ename": "KeyError",
"output_type": "stream", "evalue": "'score'",
"text": [ "output_type": "error",
"75.0\n" "traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-74-db35edb063dc>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mrecord\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mjson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mload\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'tests.json'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m'r'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mcnt\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0msum\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0mrecord\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'score'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msum\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mcnt\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mKeyError\u001b[0m: 'score'"
] ]
} }
], ],
...@@ -459,7 +463,7 @@ ...@@ -459,7 +463,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 19, "execution_count": 72,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
...@@ -479,7 +483,7 @@ ...@@ -479,7 +483,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 21, "execution_count": 75,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -533,6 +537,12 @@ ...@@ -533,6 +537,12 @@
" <td>NaN</td>\n", " <td>NaN</td>\n",
" <td>76.0</td>\n", " <td>76.0</td>\n",
" </tr>\n", " </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>Fred</td>\n",
" <td>NaN</td>\n",
" <td>76.0</td>\n",
" </tr>\n",
" </tbody>\n", " </tbody>\n",
"</table>\n", "</table>\n",
"</div>" "</div>"
...@@ -542,10 +552,11 @@ ...@@ -542,10 +552,11 @@
"0 Jared 77.0 NaN\n", "0 Jared 77.0 NaN\n",
"1 Sylvie 82.0 NaN\n", "1 Sylvie 82.0 NaN\n",
"2 Bud 66.0 NaN\n", "2 Bud 66.0 NaN\n",
"3 Fred NaN 76.0" "3 Fred NaN 76.0\n",
"4 Fred NaN 76.0"
] ]
}, },
"execution_count": 21, "execution_count": 75,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -568,7 +579,7 @@ ...@@ -568,7 +579,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 36, "execution_count": 76,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -577,7 +588,7 @@ ...@@ -577,7 +588,7 @@
"75.0" "75.0"
] ]
}, },
"execution_count": 36, "execution_count": 76,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -597,7 +608,7 @@ ...@@ -597,7 +608,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 44, "execution_count": 77,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -912,7 +923,7 @@ ...@@ -912,7 +923,7 @@
" '.timestamp_ms': '1519765900661'}" " '.timestamp_ms': '1519765900661'}"
] ]
}, },
"execution_count": 44, "execution_count": 77,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -936,7 +947,7 @@ ...@@ -936,7 +947,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 43, "execution_count": 78,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -1041,7 +1052,7 @@ ...@@ -1041,7 +1052,7 @@
"[1 rows x 140 columns]" "[1 rows x 140 columns]"
] ]
}, },
"execution_count": 43, "execution_count": 78,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -1055,16 +1066,114 @@ ...@@ -1055,16 +1066,114 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"We're going to now simplify this data a bit so it is easier to use. Let's strip out all of the retweet-related attributes." "We're going to now simplify this data a bit so it is easier to use. Let's strip out all of the retweet-related attributes and entity related-attributes."
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 79,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>.created_at</th>\n",
" <th>.id</th>\n",
" <th>.id_str</th>\n",
" <th>.text</th>\n",
" <th>.truncated</th>\n",
" <th>.user.id</th>\n",
" <th>.user.id_str</th>\n",
" <th>.user.name</th>\n",
" <th>.user.screen_name</th>\n",
" <th>.user.location</th>\n",
" <th>...</th>\n",
" <th>.place</th>\n",
" <th>.contributors</th>\n",
" <th>.is_quote_status</th>\n",
" <th>.quote_count</th>\n",
" <th>.favorite_count</th>\n",
" <th>.favorited</th>\n",
" <th>.possibly_sensitive</th>\n",
" <th>.filter_level</th>\n",
" <th>.lang</th>\n",
" <th>.timestamp_ms</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>Tue Feb 27 21:11:40 +0000 2018</td>\n",
" <td>968594506663669800</td>\n",
" <td>968594506663669760</td>\n",
" <td>RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나...</td>\n",
" <td>False</td>\n",
" <td>4448809940</td>\n",
" <td>4448809940</td>\n",
" <td>ayah</td>\n",
" <td>lovbyun</td>\n",
" <td>bbh iu jjh pcy kjd dks</td>\n",
" <td>...</td>\n",
" <td>None</td>\n",
" <td>None</td>\n",
" <td>False</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>False</td>\n",
" <td>False</td>\n",
" <td>low</td>\n",
" <td>ko</td>\n",
" <td>1519765900661</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"<p>1 rows × 56 columns</p>\n",
"</div>"
],
"text/plain": [
" .created_at .id .id_str \\\n",
"0 Tue Feb 27 21:11:40 +0000 2018 968594506663669800 968594506663669760 \n",
"\n",
" .text .truncated .user.id \\\n",
"0 RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나... False 4448809940 \n",
"\n",
" .user.id_str .user.name .user.screen_name .user.location ... \\\n",
"0 4448809940 ayah lovbyun bbh iu jjh pcy kjd dks ... \n",
"\n",
" .place .contributors .is_quote_status .quote_count .favorite_count \\\n",
"0 None None False 0 0 \n",
"\n",
" .favorited .possibly_sensitive .filter_level .lang .timestamp_ms \n",
"0 False False low ko 1519765900661 \n",
"\n",
"[1 rows x 56 columns]"
]
},
"execution_count": 79,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [ "source": [
"{k:flat_struct[k] for k in flat_struct if (not 'retweet' in k) } #fancy one liner to do this\n", "flat_struct = {k:flat_struct[k] for k in flat_struct if (not 'retweet' in k) and (not 'reply' in k) and (not 'entities' in k) } #fancy one liner to do this\n",
"tweet_table = pd.DataFrame([flat_struct])\n", "tweet_table = pd.DataFrame([flat_struct])\n",
"tweet_table" "tweet_table"
] ]
...@@ -1080,7 +1189,7 @@ ...@@ -1080,7 +1189,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 47, "execution_count": 59,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -1188,7 +1297,7 @@ ...@@ -1188,7 +1297,7 @@
"[1 rows x 39 columns]" "[1 rows x 39 columns]"
] ]
}, },
"execution_count": 47, "execution_count": 59,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -1208,7 +1317,7 @@ ...@@ -1208,7 +1317,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 49, "execution_count": 60,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
...@@ -1237,18 +1346,15 @@ ...@@ -1237,18 +1346,15 @@
" <th>.id_str</th>\n", " <th>.id_str</th>\n",
" <th>.text</th>\n", " <th>.text</th>\n",
" <th>.truncated</th>\n", " <th>.truncated</th>\n",
" <th>.in_reply_to_status_id</th>\n", " <th>.user.id</th>\n",
" <th>.in_reply_to_status_id_str</th>\n", " <th>.geo</th>\n",
" <th>.in_reply_to_user_id</th>\n", " <th>.coordinates</th>\n",
" <th>.in_reply_to_user_id_str</th>\n", " <th>.place</th>\n",
" <th>.in_reply_to_screen_name</th>\n", " <th>.contributors</th>\n",
" <th>...</th>\n", " <th>.is_quote_status</th>\n",
" <th>.entities.user_mentions</th>\n", " <th>.quote_count</th>\n",
" <th>.entities.symbols</th>\n", " <th>.favorite_count</th>\n",
" <th>.entities.media</th>\n",
" <th>.extended_entities.media</th>\n",
" <th>.favorited</th>\n", " <th>.favorited</th>\n",
" <th>.retweeted</th>\n",
" <th>.possibly_sensitive</th>\n", " <th>.possibly_sensitive</th>\n",
" <th>.filter_level</th>\n", " <th>.filter_level</th>\n",
" <th>.lang</th>\n", " <th>.lang</th>\n",
...@@ -1263,17 +1369,14 @@ ...@@ -1263,17 +1369,14 @@
" <td>968594506663669760</td>\n", " <td>968594506663669760</td>\n",
" <td>RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나...</td>\n", " <td>RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나...</td>\n",
" <td>False</td>\n", " <td>False</td>\n",
" <td>4448809940</td>\n",
" <td>None</td>\n", " <td>None</td>\n",
" <td>None</td>\n", " <td>None</td>\n",
" <td>None</td>\n", " <td>None</td>\n",
" <td>None</td>\n", " <td>None</td>\n",
" <td>None</td>\n",
" <td>...</td>\n",
" <td>[{'screen_name': 'honeydrop_506', 'name': 'HON...</td>\n",
" <td>[]</td>\n",
" <td>[{'id': 968129121061490700, 'id_str': '9681291...</td>\n",
" <td>[{'id': 968129121061490700, 'id_str': '9681291...</td>\n",
" <td>False</td>\n", " <td>False</td>\n",
" <td>0</td>\n",
" <td>0</td>\n",
" <td>False</td>\n", " <td>False</td>\n",
" <td>False</td>\n", " <td>False</td>\n",
" <td>low</td>\n", " <td>low</td>\n",
...@@ -1282,38 +1385,26 @@ ...@@ -1282,38 +1385,26 @@
" </tr>\n", " </tr>\n",
" </tbody>\n", " </tbody>\n",
"</table>\n", "</table>\n",
"<p>1 rows × 102 columns</p>\n",
"</div>" "</div>"
], ],
"text/plain": [ "text/plain": [
" .created_at .id .id_str \\\n", " .created_at .id .id_str \\\n",
"0 Tue Feb 27 21:11:40 +0000 2018 968594506663669800 968594506663669760 \n", "0 Tue Feb 27 21:11:40 +0000 2018 968594506663669800 968594506663669760 \n",
"\n", "\n",
" .text .truncated \\\n", " .text .truncated .user.id \\\n",
"0 RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나... False \n", "0 RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나... False 4448809940 \n",
"\n",
" .in_reply_to_status_id .in_reply_to_status_id_str .in_reply_to_user_id \\\n",
"0 None None None \n",
"\n",
" .in_reply_to_user_id_str .in_reply_to_screen_name ... \\\n",
"0 None None ... \n",
"\n", "\n",
" .entities.user_mentions .entities.symbols \\\n", " .geo .coordinates .place .contributors .is_quote_status .quote_count \\\n",
"0 [{'screen_name': 'honeydrop_506', 'name': 'HON... [] \n", "0 None None None None False 0 \n",
"\n", "\n",
" .entities.media \\\n", " .favorite_count .favorited .possibly_sensitive .filter_level .lang \\\n",
"0 [{'id': 968129121061490700, 'id_str': '9681291... \n", "0 0 False False low ko \n",
"\n", "\n",
" .extended_entities.media .favorited .retweeted \\\n", " .timestamp_ms \n",
"0 [{'id': 968129121061490700, 'id_str': '9681291... False False \n", "0 1519765900661 "
"\n",
" .possibly_sensitive .filter_level .lang .timestamp_ms \n",
"0 False low ko 1519765900661 \n",
"\n",
"[1 rows x 102 columns]"
] ]
}, },
"execution_count": 49, "execution_count": 60,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -1333,8 +1424,10 @@ ...@@ -1333,8 +1424,10 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 50, "execution_count": 61,
"metadata": {}, "metadata": {
"scrolled": true
},
"outputs": [ "outputs": [
{ {
"data": { "data": {
...@@ -1362,11 +1455,11 @@ ...@@ -1362,11 +1455,11 @@
" <th>.id_str</th>\n", " <th>.id_str</th>\n",
" <th>.text</th>\n", " <th>.text</th>\n",
" <th>.truncated</th>\n", " <th>.truncated</th>\n",
" <th>.in_reply_to_status_id</th>\n", " <th>.user.id</th>\n",
" <th>.in_reply_to_status_id_str</th>\n", " <th>.geo</th>\n",
" <th>.in_reply_to_user_id</th>\n", " <th>.coordinates</th>\n",
" <th>.in_reply_to_user_id_str</th>\n", " <th>.place</th>\n",
" <th>.in_reply_to_screen_name</th>\n", " <th>.contributors</th>\n",
" <th>...</th>\n", " <th>...</th>\n",
" <th>.user.profile_text_color</th>\n", " <th>.user.profile_text_color</th>\n",
" <th>.user.profile_use_background_image</th>\n", " <th>.user.profile_use_background_image</th>\n",
...@@ -1388,7 +1481,7 @@ ...@@ -1388,7 +1481,7 @@
" <td>968594506663669760</td>\n", " <td>968594506663669760</td>\n",
" <td>RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나...</td>\n", " <td>RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나...</td>\n",
" <td>False</td>\n", " <td>False</td>\n",
" <td>None</td>\n", " <td>4448809940</td>\n",
" <td>None</td>\n", " <td>None</td>\n",
" <td>None</td>\n", " <td>None</td>\n",
" <td>None</td>\n", " <td>None</td>\n",
...@@ -1407,24 +1500,21 @@ ...@@ -1407,24 +1500,21 @@
" </tr>\n", " </tr>\n",
" </tbody>\n", " </tbody>\n",
"</table>\n", "</table>\n",
"<p>1 rows × 140 columns</p>\n", "<p>1 rows × 56 columns</p>\n",
"</div>" "</div>"
], ],
"text/plain": [ "text/plain": [
" .created_at .id .id_str \\\n", " .created_at .id .id_str \\\n",
"0 Tue Feb 27 21:11:40 +0000 2018 968594506663669800 968594506663669760 \n", "0 Tue Feb 27 21:11:40 +0000 2018 968594506663669800 968594506663669760 \n",
"\n", "\n",
" .text .truncated \\\n", " .text .truncated .user.id \\\n",
"0 RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나... False \n", "0 RT @honeydrop_506: 180222 ICN #백현 #BAEKHYUNnn나... False 4448809940 \n",
"\n",
" .in_reply_to_status_id .in_reply_to_status_id_str .in_reply_to_user_id \\\n",
"0 None None None \n",
"\n", "\n",
" .in_reply_to_user_id_str .in_reply_to_screen_name ... \\\n", " .geo .coordinates .place .contributors ... .user.profile_text_color \\\n",
"0 None None ... \n", "0 None None None None ... 000000 \n",
"\n", "\n",
" .user.profile_text_color .user.profile_use_background_image \\\n", " .user.profile_use_background_image \\\n",
"0 000000 False \n", "0 False \n",
"\n", "\n",
" .user.profile_image_url \\\n", " .user.profile_image_url \\\n",
"0 http://pbs.twimg.com/profile_images/9671303202... \n", "0 http://pbs.twimg.com/profile_images/9671303202... \n",
...@@ -1435,16 +1525,16 @@ ...@@ -1435,16 +1525,16 @@
" .user.profile_banner_url .user.default_profile \\\n", " .user.profile_banner_url .user.default_profile \\\n",
"0 https://pbs.twimg.com/profile_banners/44488099... False \n", "0 https://pbs.twimg.com/profile_banners/44488099... False \n",
"\n", "\n",
" .user.default_profile_image .user.following .user.follow_request_sent \\\n", " .user.default_profile_image .user.following .user.follow_request_sent \\\n",
"0 False None None \n", "0 False None None \n",
"\n", "\n",
" .user.notifications \n", " .user.notifications \n",
"0 None \n", "0 None \n",
"\n", "\n",
"[1 rows x 140 columns]" "[1 rows x 56 columns]"
] ]
}, },
"execution_count": 50, "execution_count": 61,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
...@@ -1457,8 +1547,13 @@ ...@@ -1457,8 +1547,13 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"The process of factoring tables " "The process of factoring big tables into smaller ones is called normalization."
] ]
},
{
"cell_type": "markdown",
"metadata": {},
"source": []
} }
], ],
"metadata": { "metadata": {
......
{"a": 1, "b": 2, "c": [1, 2, 3]} {"a": 1, "b": 5, "c": [1, 2, 3]}
\ No newline at end of file \ No newline at end of file
No preview for this file type
[{"name": "Jared", "score": 77}, {"name": "Sylvie", "score": 82}, {"name": "Bud", "score": 66}] [{"name": "Jared", "score": 77}, {"name": "Sylvie", "score": 82}, {"name": "Bud", "score": 66}, {"name": "Fred", "grade": 76}, {"name": "Fred", "grade": 76}]
\ No newline at end of file \ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment