Pandas¶
Pandas is a an open source library providing high-performance, easy-to-use data structures and data analysis tools. Pandas is particularly suited to the analysis of tabular data, i.e. data that can can go into a table. In other words, if you can imagine the data in an Excel spreadsheet, then Pandas is the tool for the job.
A recent analysis of questions from Stack Overflow showed that python is the fastest growing and most widely used programming language in the world (in developed countries).
A follow-up analysis showed that this growth is driven by the data science packages such as numpy, matplotlib, and especially pandas.
The exponential growth of pandas is due to the fact that it just works. It saves you time and helps you do science more efficiently and effictively.
Pandas capabilities (from the Pandas website):¶
- A fast and efficient DataFrame object for data manipulation with integrated indexing;
- Tools for reading and writing data between in-memory data structures and different formats: CSV and text files, Microsoft Excel, SQL databases, and the fast HDF5 format;
- Intelligent data alignment and integrated handling of missing data: gain automatic label-based alignment in computations and easily manipulate messy data into an orderly form;
- Flexible reshaping and pivoting of data sets;
- Intelligent label-based slicing, fancy indexing, and subsetting of large data sets;
- Columns can be inserted and deleted from data structures for size mutability;
- Aggregating or transforming data with a powerful group by engine allowing split-apply-combine operations on data sets;
- High performance merging and joining of data sets;
- Hierarchical axis indexing provides an intuitive way of working with high-dimensional data in a lower-dimensional data structure;
- Time series-functionality: date range generation and frequency conversion, moving window statistics, moving window linear regressions, date shifting and lagging. Even create domain-specific time offsets and join time series without losing data;
- Highly optimized for performance, with critical code paths written in Cython or C.
- Python with pandas is in use in a wide variety of academic and commercial domains, including Finance, Neuroscience, Economics, Statistics, Advertising, Web Analytics, and more.
In this lecture, we will go over the basic capabilities of Pandas. It is a very deep library, and you will need to dig into the documentation for more advanced usage.
Pandas was created by Wes McKinney. Many of the examples here are drawn from Wes McKinney's book Python for Data Analysis, which includes a github repo of code samples.
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
Pandas Data Structures: Series¶
A Series represents a one-dimensional array of data. The main difference between a Series and numpy array is that a Series has an index. The index contains the labels that we use to access the data.
There are many ways to create a Series. We will just show a few.
names = ['Ryan', 'Chiara', 'Johnny']
values = [36, 37, 2.7]
ages = pd.Series(values, index=names)
ages
Series have built in plotting methods.
ages.plot(kind='bar')
Arithmetic operations and most numpy function can be applied to Series. An important point is that the Series keep their index during such operations.
np.log(ages) / ages**2
We can access the underlying index object if we need to:
ages.index
Indexing¶
We can get values back out using the index via the .loc
attribute
ages.loc['Johnny']
Or by raw position using .iloc
ages.iloc[2]
We can pass a list or array to loc to get multiple rows back:
ages.loc[['Ryan', 'Johnny']]
And we can even use slice notation
ages.loc['Ryan':'Johnny']
ages.iloc[:2]
If we need to, we can always get the raw data back out as well
ages.values # a numpy array
ages.index # a pandas Index object
Pandas Data Structures: DataFrame¶
There is a lot more to Series, but they are limit to a single "column". A more useful Pandas data structure is the DataFrame. A DataFrame is basically a bunch of series that share the same index. It's a lot like a table in a spreadsheet.
Below we create a DataFrame.
# first we create a dictionary
data = {'age': [36, 37, 1.7],
'height': [180, 155, 90],
'weight': [78, np.nan, 11.3]}
df = pd.DataFrame(data, index=['Ryan', 'Chiara', 'Johnny'])
df
Pandas handles missing data very elegantly, keeping track of it through all calculations.
df.info()
A wide range of statistical functions are available on both Series and DataFrames.
df.min()
df.mean()
df.std()
df.describe()
We can get a single column as a Series using python's getitem syntax on the DataFrame object.
df['height']
...or using attribute syntax.
df.height
Indexing works very similar to series
df.loc['Johnny']
df.iloc[2]
But we can also specify the column we want to access
df.loc['Johnny', 'age']
df.iloc[:2, 0]
If we make a calculation using columns from the DataFrame, it will keep the same index:
df.weight / df.height
Which we can easily add as another column to the DataFrame:
df['density'] = df.weight / df.height
df
Merging Data¶
Pandas supports a wide range of methods for merging different datasets. These are described extensively in the documentation. Here we just give a few examples.
education = pd.Series(['PhD', 'PhD', None, 'masters'],
index=['Ryan', 'Chiara', 'Johnny', 'Xiaomeng'],
name='education')
education
# returns a new DataFrame
df.join(education)
# returns a new DataFrame
df.join(education, how='right')
# returns a new DataFrame
everyone = df.reindex(['Ryan', 'Chiara', 'Johnny', 'Xiaomeng', 'Lorenzo'])
everyone
We can also index using a boolean series. This is very useful
adults = df[df.age > 18]
adults
df['is_adult'] = df.age > 18
df
Modifying Values¶
We often want to modify values in a dataframe based on some rule. To modify values, we need to use .loc
or .iloc
df.loc['Johnny', 'height'] = 95
df.loc['Ryan', 'weight'] += 1
df
Plotting¶
DataFrames have all kinds of useful plotting built in.
df.plot(kind='scatter', x='age', y='height', grid=True)
df.plot(kind='bar')
Time Indexes¶
Indexes are very powerful. They are a big part of why Pandas is so useful. There are different indices for different types of data. Time Indexes are especially great!
two_years = pd.date_range(start='2014-01-01', end='2016-01-01', freq='D')
timeseries = pd.Series(np.sin(2 *np.pi *two_years.dayofyear / 365),
index=two_years)
timeseries.plot()
We can use python's slicing notation inside .loc
to select a date range.
timeseries.loc['2015-01-01':'2015-07-01'].plot()
The TimeIndex object has lots of useful attributes
timeseries.index.month
timeseries.index.day
Reading Data Files: Weather Station Data¶
In this example, we will use NOAA weather station data from https://www.ncdc.noaa.gov/data-access/land-based-station-data.
The details of files we are going to read are described in this README file.
# some shell code to download some data
! wget ftp://ftp.ncdc.noaa.gov/pub/data/uscrn/products/daily01/HEADERS.txt
! wget ftp://ftp.ncdc.noaa.gov/pub/data/uscrn/products/daily01/2017/CRND0103-2017-NY_Millbrook_3_W.txt
! head -2 HEADERS.txt | tail -1 > data.txt
! cat CRND0103-2017-NY_Millbrook_3_W.txt >> data.txt
We now have a text file on our hard drive called data.txt
. Examine it.
To read it into pandas, we will use the read_csv function. This function is incredibly complex and powerful. You can use it to extract data from almost any text file. However, you need to understand how to use its various options.
With no options, this is what we get.
df = pd.read_csv('data.txt')
df.head()
Pandas failed to identify the different columns. This is because it was expecting standard CSV (comma-separated values) file. In our file, instead, the values are separated by whitespace. And not a single whilespace--the amount of whitespace between values varies. We can tell pandas this using the sep
keyword.
df = pd.read_csv('data.txt', sep='\s+')
df.head()
Great! It worked.
If we look closely, we will see there are lots of -99 and -9999 values in the file. The README file tells us that these are values used to represent missing data. Let's tell this to pandas.
df = pd.read_csv('data.txt', sep='\s+', na_values=[-9999.0, -99.0])
df.head()
Great. The missing data is now represented by NaN
.
What data types did pandas infer?
df.info()
One problem here is that pandas did not recognize the LDT_DATE
column as a date. Let's help it.
df = pd.read_csv('data.txt', sep='\s+',
na_values=[-9999.0, -99.0],
parse_dates=[1])
df.info()
It worked! Finally, let's tell pandas to use the date column as the index.
df = df.set_index('LST_DATE')
df.head()
We can now access values by time:
df.loc['2017-08-07']
Or use slicing to get a range:
df.loc['2017-07-01':'2017-07-31']
Quick Statistics¶
df.describe()
Plotting Values¶
We can now quickly make plots of the data
fig, ax = plt.subplots(ncols=2, nrows=2, figsize=(14,14))
df.iloc[:, 4:8].boxplot(ax=ax[0,0])
df.iloc[:, 10:14].boxplot(ax=ax[0,1])
df.iloc[:, 14:17].boxplot(ax=ax[1,0])
df.iloc[:, 18:22].boxplot(ax=ax[1,1])
ax[1, 1].set_xticklabels(ax[1, 1].get_xticklabels(), rotation=90);
Pandas is very "time aware":
df.T_DAILY_MEAN.plot()
Note: we could also manually create an axis and plot into it.
fig, ax = plt.subplots()
df.T_DAILY_MEAN.plot(ax=ax)
ax.set_title('Pandas Made This!')
df[['T_DAILY_MIN', 'T_DAILY_MEAN', 'T_DAILY_MAX']].plot()
Resampling¶
Since pandas understands time, we can use it to do resampling.
# monthly reampler object
rs_obj = df.resample('MS')
rs_obj
rs_obj.mean()
We can chain all of that together
df_mm = df.resample('MS').mean()
df_mm[['T_DAILY_MIN', 'T_DAILY_MEAN', 'T_DAILY_MAX']].plot()
Next time we will dig deeper into resampling, rolling means, and grouping operations (groupby).