Pandas Basics
DS 2023 | Communicating with Data
Overview¶
This notebook covers some of the basics of using Pandas.
It is meant to get you acquainted with how Pandas does some common data operations, not to provide in depth coverage of the library.
Basic operations include filtering and selecting data from an existing dataset.
Set Up¶
In this notebook, We will use the nycflights13 dataset, which contains every flight that departed from a New York City airport in 2013. The data comes from the US Bureau of Transportation Statistics.
Here is a data dictionary for the dataset:
| Variable Name | Data Type | Description |
|---|---|---|
| year, month, day | Integer | Date of departure. |
| dep_time, arr_time | Integer | Actual departure and arrival times (Format: Local time, HHMM or HMM). Missing values (NA) represent canceled flights. |
| sched_dep_time, sched_arr_time | Integer | Scheduled departure and arrival times (Format: Local time, HHMM or HMM). |
| dep_delay, arr_delay | Float | Departure and arrival delays, measured in minutes. Negative times represent early departures/arrivals. |
| carrier | String | Two-letter airline carrier abbreviation (maps to the airlines table). |
| flight | Integer | Flight number. |
| tailnum | String | Aircraft tail number (maps to the planes table). Missing values (NA) represent canceled flights. |
| origin | String | Origin airport code (EWR, JFK, or LGA; maps to airports and weather). |
| dest | String | Destination airport code (maps to airports). |
| air_time | Float | Amount of time spent in the air, measured in minutes. |
| distance | Float | Distance between origin and destination airports, measured in miles. |
| hour, minute | Float | Scheduled departure time broken down into hour and minute components. |
| time_hour | datetime | Scheduled date and time of the flight formatted as a timestamp (YYYY-MM-DD HH:MM:SS). Used for joining directly with the weather table. |
import pandas as pd
flight_data_url = "https://virginia.box.com/shared/static/hby5hxuvurkmatdxgy0p1ua7oftwl6i9.csv"
flights = pd.read_csv(flight_data_url)Inspect the data¶
This dataset contains all flights that departed New York City in 2013.
flightsThe info method¶
The .info() method gives a compact structural overview: column names, data types, and how many non-missing values each column has.
This gives us information on the name and data type of each column, as well as how many non-null values are in each column.
flights.info()<class 'pandas.DataFrame'>
RangeIndex: 336776 entries, 0 to 336775
Data columns (total 20 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Unnamed: 0 336776 non-null int64
1 year 336776 non-null int64
2 month 336776 non-null int64
3 day 336776 non-null int64
4 dep_time 328521 non-null float64
5 sched_dep_time 336776 non-null int64
6 dep_delay 328521 non-null float64
7 arr_time 328063 non-null float64
8 sched_arr_time 336776 non-null int64
9 arr_delay 327346 non-null float64
10 carrier 336776 non-null str
11 flight 336776 non-null int64
12 tailnum 334264 non-null str
13 origin 336776 non-null str
14 dest 336776 non-null str
15 air_time 327346 non-null float64
16 distance 336776 non-null int64
17 hour 336776 non-null int64
18 minute 336776 non-null int64
19 time_hour 336776 non-null str
dtypes: float64(5), int64(10), str(5)
memory usage: 62.0 MB
A quick note on Pandas’ methods¶
Most of Pandas’ core operations are methods.
These are called with . directly on the object, in this case flights.
For example, to get the top rows in a dataframe, we call the .head() method.
flights.head()How many rows and columns are in the dataframe?¶
The number of rows and columns in a dataframe is called its shape.
You access this information by calling the dataframe’s shape attribute, like so:
flights.shape(336776, 20)Note that it returns a tuple.
If you were only interested in finding out out how many rows are in the dataset, you can do this:
flights.shape[0]336776Or, you could use Python’s len() function, which works on any list-like object:
len(flights)336776Are the data tidy?¶
Always begin by asking this question.
If they data are not tidy, what shape are they in (literally)?
Does the dataset need to be reshaped in any way?
If they are tidy, what is the unit of observation?
In this case, the dataset is tidy and the unit of observation is the specific flight -- the taking off and landing of a specific airplane.
Classify the columns¶
The next thing to do is identify the column types.
Are there any identifiers? Groupers? Measurements?
Are there any redundant columns? These are columns that repeat data in other columns.
Are there any analytical columns? These are columns that are computed from one or more other columns.
The columns attribute¶
Here, we grab the list of columns from the dataset using the columns attribute of the dataframe.
Using the information we got from .info(), we can identify the column uses.
Note we are using the column number offsets to combine slices of the column list to create our new lists.
cols = list(flights.columns)
cols['Unnamed: 0',
'year',
'month',
'day',
'dep_time',
'sched_dep_time',
'dep_delay',
'arr_time',
'sched_arr_time',
'arr_delay',
'carrier',
'flight',
'tailnum',
'origin',
'dest',
'air_time',
'distance',
'hour',
'minute',
'time_hour']group_cols = cols[1:4] + cols[10:15] + cols[17:19]
group_cols['year',
'month',
'day',
'carrier',
'flight',
'tailnum',
'origin',
'dest',
'hour',
'minute']measure_cols = cols[4:10] + cols[15:17]
measure_cols['dep_time',
'sched_dep_time',
'dep_delay',
'arr_time',
'sched_arr_time',
'arr_delay',
'air_time',
'distance']There are no identifying columns, and there are two redundant ones: time_hour and Unnamed: 0.
The Unnamed: 0 column is an artifact of the import process. It gave this name to the unnamed first column in the CSV file, which clearly stands for the row number.
Filtering rows¶
One of the most important operations to perform on a dataframe is filtering.
Filtering grabs a subset of rows based on some specified conditions.
For example, we may want to see only rows for a certain year and month.
The query method¶
We can use .query() to do this. It works by passing a condition expressed as a string.
For example, to see all flights for February 2013, we would do this:
flights.query("year == 2013 & month == 2")Here is a query for flights delayed more than 120 minutes:
flights.query("dep_delay > 120")The indexer method¶
You also filter by supplying the two expressions directly to the dataframe’s indexer, which you can access by using two square brackets at the end of the variable name, e.g. flights[].
Note that the two boolean expressions are enclosed in parentheses.
flights[(flights['year'] == 2013) & (flights['month'] == 2)]The loc accessor method¶
You can also query by using Pandas’ loc accessor method to do queries.
flights.loc[flights['dep_delay'] > 120]Sorting rows with sort_values¶
The method .sort_values() changes the order of rows based on the value of one or more columns.
It takes a list of column names, or a single column name, to sort by.
The ascending argument determines the resulting sort order, whether from least to greatest (asending = True) or not. The default value is True, so if we want reverse sort order we set it to False.
flights.sort_values('dep_delay', ascending=False)Note that the number of rows hasn’t changed. Sorting rearranges the data, it doesn’t filter it.
Removing duplicate rows with drop_duplicates¶
.drop_duplicates() finds unique rows in a dataset.
flights1 = flights.drop_duplicates()We can compare the lengths of the two dataframes to see if there are any duplicates.
len(flights) == len(flights1)TrueTurns out there aren’t.
Creating new columns¶
You can create new columns by naming them in the indexer and then assigning a value to them.
Let’s compute the gain (how much time a delayed flight made up in the air) and the speed in miles per hour:
flights['gain'] = flights['dep_delay'] - flights['arr_delay']
flights['speed'] = flights["distance"] / flights["air_time"] * 60
flightsSelecting columns¶
Another important operation to perform on a dataframe is to select a subset of columns.
Sometimes you do this because there are too many columns to see on one page. Other times, you want to zoom in on a few columns for exploratory purposes.
To select columns, we just pass a list of column names to the dataframe.
flights[["year", "month", "day"]]Note that we can pass a list of columns in a different order than how they appear in the dataframe.
flights[["year", "day", "month"]]We can also select a range of columns by position with loc method.
The : in the expression below means all rows — we’ll look at this function more below.
flights.loc[:, "year":"day"]We can use our column lists from above to select, too.
flights[group_cols]flights[measure_cols]Combining filtering and selecting with loc¶
With the loc method, you can combine filtering and selecting.
In the first argument, you can put a filtering expression. This is usually a boolean expression applied to one or more columns in the dataframe.
In the second argument, you can put a selecting expression. The is usually a list of columns names.
Think of it this way:
df.loc[rowwise_expression, columnwise_expresson]For example:
flights.loc[flights.month == 1, ['dep_time','dep_delay']]Computing stats¶
The whole point of a dataframe is to be able to compute statistical and other mathematical properties from the data.
Here are a couple of quick things you can do.
Get the number of values in a column or combination of columns with value_counts¶
You can use value_counts() to quickly count the number of rows associated with one or more columns:
flights.value_counts('carrier')carrier
UA 58665
B6 54635
EV 54173
DL 48110
AA 32729
MQ 26397
US 20536
9E 18460
WN 12275
VX 5162
FL 3260
AS 714
F9 685
YV 601
HA 342
OO 32
Name: count, dtype: int64flights.value_counts(['origin','dest'])origin dest
JFK LAX 11262
LGA ATL 10263
ORD 8857
JFK SFO 8204
LGA CLT 6168
...
JFK MEM 1
STL 1
LGA LEX 1
JFK BHM 1
EWR LGA 1
Name: count, Length: 224, dtype: int64Note that value_counts returns a series , not a dataframe.
If want a dataframe, we can use the .to_frame() method.
flights.value_counts(['origin','dest']).to_frame('n')Note also the .value_counts() returns a series with an index for the counted columns.
When we have at least two grouping columns in the index, unstack the results, since the count is a measurement.
Here we see a wide table showing the top 20 most frequent origin and destination combinations.
flights.value_counts(['origin','dest']).head(20).unstack(fill_value=0)Computing aggregate values¶
You can compute aggregate values in many ways in Pandas. Here are two of the most common.
One is to just apply the aggregate function to one or more columns.
Here we get the mean value of each of our measurement columns.
flights[measure_cols].mean()dep_time 1349.109947
sched_dep_time 1344.254840
dep_delay 12.639070
arr_time 1502.054999
sched_arr_time 1536.380220
arr_delay 6.895377
air_time 150.686460
distance 1039.912604
dtype: float64We can also pass the aggregation function name to the .agg() method.
flights[measure_cols].agg('mean')dep_time 1349.109947
sched_dep_time 1344.254840
dep_delay 12.639070
arr_time 1502.054999
sched_arr_time 1536.380220
arr_delay 6.895377
air_time 150.686460
distance 1039.912604
dtype: float64The .agg() method has the advantage of being able to take more than one function.
Here we get the mean, median, and standard deviation.
flights[measure_cols].agg(['mean','median','std'])We can transpose the table with the .T operator to turn the columns into observations.
flights[measure_cols].agg(['mean','median','std']).TUsing .groupby()¶
We can also use the .groupby() method to compute joint aggregate values on combinations of columns.
Here we get the mean values for all of our measure columns for each carrier to each airport.
flights.groupby(['carrier','dest'])[measure_cols].mean()Note that .groupby() also returns a series with an index.
In this case, we can unstack the results on any of our aggregate measures, like so:
flights.groupby(['carrier','dest'])['dep_delay'].mean().unstack(fill_value=0).style.format(precision=0)Chaining it all together¶
You’ve now seen several individual operations.
It is possible to combine these operations.
For example, if you wanted to mean arrival delay per day, you need to combine filtering, creating a new column, selecting columns, and sorting.
All in one pipeline:
flights.query('dest == "CHO"')\
.groupby(["year", "month", "day"])\
.agg(arr_delay=("arr_delay", "mean"))\
.reset_index()\
.head(10)Note the use of backslashes. These allow us to write a single Python expression over multiple lines.
Instead of using backslashes, we can just wrap everything in parentheses.
(
flights
.query('dest == "CHO"')
.groupby(["year", "month", "day"])
.agg(arr_delay=("arr_delay", "mean"))
.reset_index()
.head()
)Finally, here is the same set of operations using the indexer syntax.
(
flights[flights['dest'] == 'CHO']
.groupby(["year", "month", "day"])['arr_delay']
.mean()
.to_frame('arr_delay')
.reset_index()
.head()
)