This series is about how to make effective use of pandas, a data analysis library for the Python programming language. It's targeted at an intermediate level: people who have some experience with pandas, but are looking to improve.
There are many great resources for learning pandas; this is not one of them. For beginners, I typically recommend Greg Reda's 3-part introduction, especially if they're familiar with SQL. Of course, there's the pandas documentation itself. I gave a talk at PyData Seattle targeted as an introduction if you prefer video form. Wes McKinney's Python for Data Analysis is still the goto book (and is also a really good introduction to NumPy as well). Jake VanderPlas's Python Data Science Handbook, in early release, is great too. Kevin Markham has a video series for beginners learning pandas.
With all those resources (and many more that I've slighted through omission), why write another? Surely the law of diminishing returns is kicking in by now. Still, I thought there was room for a guide that is up to date (as of March 2016) and emphasizes idiomatic pandas code (code that is pandorable). This series probably won't be appropriate for people completely new to python or NumPy and pandas. By luck, this first post happened to cover topics that are relatively introductory, so read some of the linked material and come back, or let me know if you have questions.
We'll be working with flight delay data from the BTS (R users can install Hadley's NYCFlights13 dataset for similar data.
import os
import zipfile
import requests
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
if int(os.environ.get("MODERN_PANDAS_EPUB", 0)):
import prep
import requests
headers = {
'Referer': 'https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236&DB_Short_Name=On-Time',
'Origin': 'https://www.transtats.bts.gov',
'Content-Type': 'application/x-www-form-urlencoded',
}
params = (
('Table_ID', '236'),
('Has_Group', '3'),
('Is_Zipped', '0'),
)
with open('modern-1-url.txt', encoding='utf-8') as f:
data = f.read().strip()
os.makedirs('data', exist_ok=True)
dest = "data/flights.csv.zip"
if not os.path.exists(dest):
r = requests.post('https://www.transtats.bts.gov/DownLoad_Table.asp',
headers=headers, params=params, data=data, stream=True)
with open("data/flights.csv.zip", 'wb') as f:
for chunk in r.iter_content(chunk_size=102400):
if chunk:
f.write(chunk)
That download returned a ZIP file. There's an open Pull Request for automatically decompressing ZIP archives with a single CSV, but for now we have to extract it ourselves and then read it in.
zf = zipfile.ZipFile("data/flights.csv.zip")
fp = zf.extract(zf.filelist[0].filename, path='data/')
df = pd.read_csv(fp, parse_dates=["FL_DATE"]).rename(columns=str.lower)
df.info()
Or, explicit is better than implicit. By my count, 7 of the top-15 voted pandas questions on Stackoverflow are about indexing. This seems as good a place as any to start.
By indexing, we mean the selection of subsets of a DataFrame or Series.
DataFrames
(and to a lesser extent, Series
) provide a difficult set of challenges:
slice
s.The complexity of pandas' indexing is a microcosm for the complexity of the pandas API in general. There's a reason for the complexity (well, most of it), but that's not much consolation while you're learning. Still, all of these ways of indexing really are useful enough to justify their inclusion in the library.
Or, explicit is better than implicit.
By my count, 7 of the top-15 voted pandas questions on Stackoverflow are about slicing. This seems as good a place as any to start.
Brief history digression: For years the preferred method for row and/or column selection was .ix
.
df.ix[10:15, ['fl_date', 'tail_num']]
However this simple little operation hides some complexity. What if, rather than our default range(n)
index, we had an integer index like
first = df.groupby('airline_id')[['fl_date', 'unique_carrier']].first()
first.head()
Can you predict ahead of time what our slice from above will give when passed to .ix
?
first.ix[10:15, ['fl_date', 'tail_num']]
Surprise, an empty DataFrame! Which in data analysis is rarely a good thing. What happened?
We had an integer index, so the call to .ix
used its label-based mode. It was looking for integer labels between 10:15 (inclusive). It didn't find any. Since we sliced a range it returned an empty DataFrame, rather than raising a KeyError.
By way of contrast, suppose we had a string index, rather than integers.
first = df.groupby('unique_carrier').first()
first.ix[10:15, ['fl_date', 'tail_num']]
And it works again! Now that we had a string index, .ix
used its positional-mode. It looked for rows 10-15 (exclusive on the right).
But you can't reliably predict what the outcome of the slice will be ahead of time. It's on the reader of the code (probably your future self) to know the dtypes so you can reckon whether .ix
will use label indexing (returning the empty DataFrame) or positional indexing (like the last example).
In general, methods whose behavior depends on the data, like .ix
dispatching to label-based indexing on integer Indexes but location-based indexing on non-integer, are hard to use correctly. We've been trying to stamp them out in pandas.
Since pandas 0.12, these tasks have been cleanly separated into two methods:
.loc
for label-based indexing.iloc
for positional indexingfirst.loc[['AA', 'AS', 'DL'], ['fl_date', 'tail_num']]
first.iloc[[0, 1, 3], [0, 1]]
.ix
is still around, and isn't being deprecated any time soon. Occasionally it's useful. But if you've been using .ix
out of habit, or if you didn't know any better, maybe give .loc
and .iloc
a shot. For the intrepid reader, Joris Van den Bossche (a core pandas dev) compiled a great overview of the pandas __getitem__
API.
A later post in this series will go into more detail on using Indexes effectively;
they are useful objects in their own right, but for now we'll move on to a closely related topic.
Pandas used to get a lot of questions about assignments seemingly not working. We'll take this StackOverflow question as a representative question.
f = pd.DataFrame({'a':[1,2,3,4,5], 'b':[10,20,30,40,50]})
f
The user wanted to take the rows of b
where a
was 3 or less, and set them equal to b / 10
We'll use boolean indexing to select those rows f['a'] <= 3
,
# ignore the context manager for now
with pd.option_context('mode.chained_assignment', None):
f[f['a'] <= 3]['b'] = f[f['a'] <= 3 ]['b'] / 10
f
And nothing happened. Well, something did happen, but nobody witnessed it. If an object without any references is modified, does it make a sound?
The warning I silenced above with the context manager links to an explanation that's quite helpful. I'll summarize the high points here.
The "failure" to update f
comes down to what's called chained indexing, a practice to be avoided.
The "chained" comes from indexing multiple times, one after another, rather than one single indexing operation.
Above we had two operations on the left-hand side, one __getitem__
and one __setitem__
(in python, the square brackets are syntactic sugar for __getitem__
or __setitem__
if it's for assignment). So f[f['a'] <= 3]['b']
becomes
getitem
: f[f['a'] <= 3]
setitem
: _['b'] = ...
# using _
to represent the result of 1.In general, pandas can't guarantee whether that first __getitem__
returns a view or a copy of the underlying data.
The changes will be made to the thing I called _
above, the result of the __getitem__
in 1
.
But we don't know that _
shares the same memory as our original f
.
And so we can't be sure that whatever changes are being made to _
will be reflected in f
.
Done properly, you would write
f.loc[f['a'] <= 3, 'b'] = f.loc[f['a'] <= 3, 'b'] / 10
f
Now this is all in a single call to __setitem__
and pandas can ensure that the assignment happens properly.
The rough rule is any time you see back-to-back square brackets, ][
, you're in asking for trouble. Replace that with a .loc[..., ...]
and you'll be set.
The other bit of advice is that a SettingWithCopy warning is raised when the assignment is made. The potential copy could be made earlier in your code.
MultiIndexes might just be my favorite feature of pandas. They let you represent higher-dimensional datasets in a familiar two-dimensional table, which my brain can sometimes handle. Each additional level of the MultiIndex represents another dimension. The cost of this is somewhat harder label indexing.
My very first bug report to pandas, back in November 2012, was about indexing into a MultiIndex. I bring it up now because I genuinely couldn't tell whether the result I got was a bug or not. Also, from that bug report
Sorry if this isn't actually a bug. Still very new to python. Thanks!
Adorable.
That operation was made much easier by this addition in 2014, which lets you slice arbitrary levels of a MultiIndex.. Let's make a MultiIndexed DataFrame to work with.
hdf = df.set_index(['unique_carrier', 'origin', 'dest', 'tail_num', 'fl_date']).sort_index()
hdf[hdf.columns[:4]].head()
And just to clear up some terminology, the levels of a MultiIndex are the
former column names (unique_carrier
, origin
...).
The labels are the actual values in a level, ('AA'
, 'ABQ'
, ...).
Levels can be referred to by name or position, with 0 being the outermost level.
Slicing the outermost index level is pretty easy, we just use our regular .loc[row_indexer, column_indexer]
. We'll select the columns dep_time
and dep_delay
where the carrier was American Airlines, Delta, or US Airways.
hdf.loc[['AA', 'DL', 'US'], ['dep_time', 'dep_delay']]
So far, so good. What if you wanted to select the rows whose origin was Chicago O'Hare (ORD
) or Des Moines International Airport (DSM).
Well, .loc
wants [row_indexer, column_indexer]
so let's wrap the two elements of our row indexer (the list of carriers and the list of origins) in a tuple to make it a single unit:
hdf.loc[(['AA', 'DL', 'US'], ['ORD', 'DSM']), ['dep_time', 'dep_delay']]
Now try to do any flight from ORD or DSM, not just from those carriers.
This used to be a pain.
You might have to turn to the .xs
method, or pass in df.index.get_level_values(0)
and zip that up with the indexers your wanted, or maybe reset the index and do a boolean mask, and set the index again... ugh.
But now, you can use an IndexSlice
.
hdf.loc[pd.IndexSlice[:, ['ORD', 'DSM']], ['dep_time', 'dep_delay']]
The :
says include every label in this level.
The IndexSlice
object is just sugar for the actual python slice
object needed to remove slice each level.
pd.IndexSlice[:, ['ORD', 'DSM']]
We use IndexSlice
since hdf.loc[(:, ['ORD', 'DSM'])]
isn't valid python syntax.
Now we can slice to our heart's content; all flights from O'Hare to Des Moines in the first half of January? Sure, why not?
hdf.loc[pd.IndexSlice[:, 'ORD', 'DSM', :, '2014-01-01':'2014-01-15'],
['dep_time', 'dep_delay', 'arr_time', 'arr_delay']]
We'll talk more about working with Indexes (including MultiIndexes) in a later post. I have an unproven thesis that they're underused because IndexSlice
is underused, causing people to think they're more unwieldy than they actually are. But let's close out part one.
This first post covered Indexing, a topic that's central to pandas.
The power provided by the DataFrame comes with some unavoidable complexities.
Best practices (using .loc
and .iloc
) will spare you many a headache.
We then toured a couple of commonly misunderstood sub-topics, setting with copy and Hierarchical Indexing.