Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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 NameData TypeDescription
year, month, dayIntegerDate of departure.
dep_time, arr_timeIntegerActual departure and arrival times (Format: Local time, HHMM or HMM). Missing values (NA) represent canceled flights.
sched_dep_time, sched_arr_timeIntegerScheduled departure and arrival times (Format: Local time, HHMM or HMM).
dep_delay, arr_delayFloatDeparture and arrival delays, measured in minutes. Negative times represent early departures/arrivals.
carrierStringTwo-letter airline carrier abbreviation (maps to the airlines table).
flightIntegerFlight number.
tailnumStringAircraft tail number (maps to the planes table). Missing values (NA) represent canceled flights.
originStringOrigin airport code (EWR, JFK, or LGA; maps to airports and weather).
destStringDestination airport code (maps to airports).
air_timeFloatAmount of time spent in the air, measured in minutes.
distanceFloatDistance between origin and destination airports, measured in miles.
hour, minuteFloatScheduled departure time broken down into hour and minute components.
time_hourdatetimeScheduled date and time of the flight formatted as a timestamp (YYYY-MM-DD HH:MM:SS). Used for joining directly with the weather table.

Inspect the data

This dataset contains all 336,776336,776 flights that departed New York City in 2013.

Loading...

The 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.

<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.

Loading...

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:

(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:

336776

Or, you could use Python’s len() function, which works on any list-like object:

336776

Are 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.

['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']
['year', 'month', 'day', 'carrier', 'flight', 'tailnum', 'origin', 'dest', 'hour', 'minute']
['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:

Loading...

Here is a query for flights delayed more than 120 minutes:

Loading...

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.

Loading...

The loc accessor method

You can also query by using Pandas’ loc accessor method to do queries.

Loading...

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.

Loading...

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.

We can compare the lengths of the two dataframes to see if there are any duplicates.

True

Turns 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:

Loading...

Selecting 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.

Loading...

Note that we can pass a list of columns in a different order than how they appear in the dataframe.

Loading...

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.

Loading...

We can use our column lists from above to select, too.

Loading...
Loading...

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:

Loading...

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:

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: int64
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: int64

Note that value_counts returns a series , not a dataframe.

If want a dataframe, we can use the .to_frame() method.

Loading...

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.

Loading...

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.

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: float64

We can also pass the aggregation function name to the .agg() method.

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: float64

The .agg() method has the advantage of being able to take more than one function.

Here we get the mean, median, and standard deviation.

Loading...

We can transpose the table with the .T operator to turn the columns into observations.

Loading...

Using .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.

Loading...

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:

Loading...

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:

Loading...

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.

Loading...

Finally, here is the same set of operations using the indexer syntax.

Loading...