{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part 1\n",
"- Dataframes\n",
"- describe()\n",
"- head()\n",
"- Series\n",
"- operations on Series\n",
"- pulling out subsets of columns"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_csv('taxi.csv')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"df is a \"pandas dataframe\"\n",
"\n",
"This is like an SQL table:\n",
"- it has fields, which have a name and a datatype\n",
"- it has rows, which have a value (or NA, which is like NULL) for each column\n",
"\n",
"Each row also has an \"index\" associated with it.\n",
"\n",
"When we output the dataframe, as in the following cell, we see the values in each row and we also see the value of the index in the first column. In this example, the index is just a number between 0 and 2302086.\n",
"\n",
"The data that is in this dataframe is the NYC taxi data, downloaded from https://www1.nyc.gov/site/tlc/about/tlc-trip-record-data.page. Each record is a taxi trip in NYC. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some of the important fields are:\n",
"- tpep_pickup_datetime: this is the date and time when the trip started. (“tpep”\n",
"stands for Taxicab Passenger Enhancements Project, which is the name of the\n",
"project that collected this data).\n",
"- tpep_dropoff_datetime: this is the date and time when the trip stopped.\n",
"- passenger_count: this is the number of passengers in the taxi\n",
"- trip_distance: this is the distance of the trip, in miles\n",
"- PULocationID: this id corresponds to a LocationId in zones, indicating the zone\n",
"in which the pickup occurred. “PU” stands for “pickup.”\n",
"- DOLocationID: this id corresponds to a LocationId in zones, indicating the zone\n",
"in which the dropoff occurred. “DO” stands for “dropoff.”\n",
"- total_amount: this is the total amount of money paid by the rider for the trip. Components of this amount are broken out across the fields fare_amount, extra, mta_tax, tip_amount, tolls_amount\n",
"\n",
"More information about the fields can be found at, https://www1.nyc.gov/assets/tlc/downloads/pdf/data_dictionary_trip_records_yellow.pdf"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Dataframes have methods associated with them, which you can call by using syntax of the form df.method(arguments)\n",
"\n",
"For example, df.head shows the first few records from the dataframe --- useful if the dataframe is big."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another nice way to explore the data is to use describe. This tells you, for each field:\n",
"- the number of non-NA records\n",
"- the mean of these records\n",
"- their standard deviation\n",
"- the minimum and maximum values\n",
"- three quartiles: 25%, 50%, 75%. The 25% quartile is the number x such that 25% of the records have a value less than or equal to x\n",
"\n",
"This is quite meaningful for some fields (like fare_amount)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can pull out an individual field from a dataframe like in the following cell. This creates a \"Series\".\n",
"\n",
"A Series is essentially a single column of a dataframe. It contains:\n",
"- A series of values (the data itself)\n",
"- The value of the corresponding index from the original dataframe\n",
"- The name of the data (here, \"total_amount\"), derived from the original dataframe.\n",
"- The number of values in the series\n",
"- The datatype for the data (here, float64)\n",
"\n",
"The following creates a series for the amount of money paid for each taxi trip."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df['total_amount']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can do operations on Series, like the following"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df['total_amount']/10"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This takes each value in the series, e.g., the first one 11.16, divides it by 10, and then returns a Series with the corresponding values.\n",
"\n",
"We can also do operations on collections of Series, like the following cell. This gives us the tip, as a fraction of the pre-tip fare."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df['tip_amount']/(df['total_amount']-df['tip_amount'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also assign variables to the results of these operations, like the following. Note that when we do this, the notebook doesn't output the value. This is because a notebook cell evaluates to the return value of the last command. When the last command is an assignment, this doesn't have a return value."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tip = df['tip_amount']/(df['total_amount']-df['tip_amount'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In addition to pulling out just one column from a dataframe, we can create a new dataframe that has a subset of its columns, like this. What this line does is to create a list of column names, ['tip_amount','total_amount'], and then pass this as an argument to df[]."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df[['tip_amount','total_amount']]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It might be easier to understand what we did in the cell above if we do it in two steps, like the following."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = ['tip_amount','total_amount']\n",
"df[x]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Question 1: How would I calculate the amount of money per mile?\n",
"- A. df[total_amount]/df[trip_distance]\n",
"- B. df['total_amount']/df['trip_distance']\n",
"- C. df[total_amount/trip_distance]\n",
"- D. df['total_amount'/'trip_distance']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Put answer to question 1 here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part 2\n",
"- Making a histogram with matplotlib\n",
"- Selecting a subset of the records (i.e., \"filtering\")\n",
"- Titles and axis labels"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"matplotlib is a really useful plotting package.\n",
"\n",
"matplotlib.pyplot is a part of matplotlib that makes it a little easier to plot."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's make a histogram of the tip percentage"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tip.hist()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This histogram might seem strange at first. There is a single bar between 0 and 100 and a lot of space on the x-axis that appears empty. Let's see what's going on."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tip.describe()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It seems that there are some very large tip fractions --- the largest is 9.5e02 = 95. This is someone who gave a tip that was 95 times larger than the untipped original fare. But most tip fractions are smaller -- the 75% quantile is 2e-01, or 20%.\n",
"\n",
"To focus on just a part of the data, we can filter. Let's create a dataset that only contains records whose tip fraction is less than or equal to 1.\n",
"\n",
"To do this, look at the following code. It produces a Series of boolean values whose index is the same as tip and the original dataframe, which is True whenever tip is <= 1, and False otherwise."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tip<=1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can then get a Series which only has the values of tip associated with indices for which tip<=1 is True. Note that this has 2300307 records, while the original tip Series had 2302087 records. This must mean that there are 2302087 - 2300307 = 1780 records where tip is strictly bigger than 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tip[tip<=1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also use this Series of boolean values to get a subset of our original dataframe, or any other Series or dataframe that uses the same index."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df[tip<=1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You might be surprised that pandas produces meaningful results in both of the following cases:\n",
"- df[tip <= 1]\n",
"- df['total_amount']\n",
"\n",
"When you call df[x], pandas looks at what is in x and then figures out what to do.\n",
"- If x is a Series using the same index as df, then pandas returns the records whose value in the Series is True.\n",
"- If x is a column name or list of column names, then pandas returns the fields with those names."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can make a histogram of this subset of the tip data. This makes a lot more sense --- most tips are somewhere between 0 and 30%."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tip[tip<=1].hist()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's a better version of this graph that would be suitable to show to an external stakeholder. It has these improvements:\n",
"- it increases the number of bins, so we can see more granularity between 0% and 20%\n",
"- It adds labels for the x- and y-axis\n",
"- It adds a title that informs the viewer that outliers have been removed\n",
"- It reports results in terms of percentages rather than fractions. Most business people are more comfortable with percentages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"(100*tip[tip<=1]).hist(bins=30)\n",
"plt.xlabel('Tip Percentage (%)')\n",
"plt.ylabel('Number of trips')\n",
"plt.title('Tip Percentage Histogram, Discarding 1780 Outliers')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part 3\n",
"- applying np.log10 to a Series\n",
"- practice manipulating data"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Whenever we remove outliers, we should dig in to understand them."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A first thing to do is to look at the original data corresponding to large tip amounts"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df[tip>1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is its own dataframe, so we can pull out just a subset of the columns to get a more refined view.\n",
"\n",
"Q2: How would we get a dataframe that includes only tip_amount and total_amount, and only those records whose tip fraction is strictly above 1?\n",
"- A. df[tip>1][['tip_amount','total_amount']]\n",
"- B. df[tip>1]['tip_amount','total_amount']\n",
"- C. df['tip_amount','total_amount'][tip>1]\n",
"- D. df[['tip_amount','total_amount']][tip>1]\n",
"- E. A and D\n",
"- F. B and C"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Plug in answer to Q2 here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From this, it seems like the data is reasonable --- occasionally people seem to give generous tips, but it doesn't seem outrageous."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also investigate tips that have a large magnitude on an absolute scale.\n",
"\n",
"Q3. Which of the following lines of code would produce a dataframe containing all fields for those trips whose tip amount (as an absolute \\\\$ value) is above \\$100.\n",
"- A. df['tip_amount'>100]\n",
"- B. df[['tip_amount'>100]]\n",
"- C. df[df['tip_amount'>100]]\n",
"- D. df[df['tip_amount']>100]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Insert answer to Q3 here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"These trips are clearly unusual. For example, second from the top we see a trip with a total fare of \\\\$360.80, of which \\\\$350 was a tip. This trip only took 0.4 miles and lasted about 15 minutes. Note that most people can walk more than 0.4 miles quite easily in 15 minutes. Looking at https://www1.nyc.gov/assets/tlc/images/content/pages/about/taxi_zone_map_manhattan.jpg, this picked up in Chelsea (68) and dropped off in Midtown (230).\n",
"\n",
"There could be a very interesting story behind this, fraud, or a data glitch.\n",
"\n",
"The fourth row has a total amount of \\\\$285.30 and a tip of \\\\$285."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another useful way to understand the distribution of these large tips is to make a histogram of the *log* of the tip fraction. To do this, we can use the log10 function from numpy. If x is a series, then np.log10(x) will produce a series whose values are the base-10 log of the values in x.\n",
"\n",
"Q4. Which of the following lines of code would produce a histogram of the base-10 log of the tip fraction, for those tip fractions bigger than 1?\n",
"- A. np.log10(tip[tip>1]).hist()\n",
"- B. np.log10(tip>1).hist()\n",
"- C. tip(np.log10(tip>1)).hist()\n",
"- D. hist(np.log10(tip>1))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Insert answer to Q3 here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Next lecture\n",
"- scatter plots\n",
"- subsampling data\n",
"- filtering with AND clauses\n",
"- group by\n",
"- joins\n",
"- pulling data from a SQL database\n",
"- manipulating data in a SQL database"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}