Pandas is a Python package for tabular data.
You may need to install pandas first
(pycourse) $ conda install pandasimport numpy as np
import matplotlib.pyplot as plt
import pandas as pd
rng = np.random.default_rng()
pd.__version__Overview¶
Pandas provides two objects:
| Name | Dimensions | Description |
|---|---|---|
pd.Series | 1 | labeled array |
pd.DataFrame | 2 | labeled table whose columns can have different types |
The main difference from a NumPy ndarray is that each column of a DataFrame can hold a different type of data (numbers, strings, booleans, ...). The name DataFrame comes from a similar object in R. Pandas also has tools for reading and writing files, handling missing data, grouping and merging tables, time series, and plotting.
Get Started¶
We’ll load the Titanic data set, which is part of seaborn’s example data. It contains information about 891 passengers on the infamous Titanic
See the Pandas tutorial on reading/writing data for more information.
titanic = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv")
df = titanic
dfWe see that there are a variety of columns. Some contain numeric values, some contain strings, some contain booleans, etc.
If you want to access a particular column, you can create a Series using the column title.
ages = df["age"] # __getitem__
agesColumn titles can also be used as attributes:
ages = df.age
agesPandas DataFrames and Series have a variety of built-in methods to examine data
print(ages.max(), ages.min(), ages.mean(), ages.median())You can display a variety of statistics using describe(). Note that NaN values are simply ignored.
ages.describe()depending on the type of data held in the series, describe has different functionality.
df['sex'].describe()You can find some more discussion in the Pandas tutorial here
Selecting Subsets of DataFrames¶
You can select multiple columns
df2 = df[["age", "survived"]]
df2If you want to select certain rows, using some sort of criteria, you can create a series of booleans
mask = df2['age'] > 30
df2[mask]We see that we only have 305 rows now
If you just want to access specific rows, you can use iloc
df.iloc[:4]Missing data¶
In data analysis, knowing how to properly fill in missing data is very important, sometimes we don’t want to just ignore them, especially when the observational numbers are small. There are various ways to do it such as filling with the mean, K-Nearest Neighbors (KNN) methods and so on.
isna marks the missing entries, so summing it counts them in each column:
titanic.isna().sum()dropna drops the rows with missing values (here, only missing values in the age column count), and fillna replaces missing values with something else.
print(titanic.shape)
print(titanic.dropna(subset=["age"]).shape)Exercise¶
Replace the missing values in the age column of the Titanic data set by the mean age, using fillna.
filled = titanic.copy()
filled["age"] = filled["age"].fillna(filled["age"].mean())
filled["age"].isna().sum()Series¶
A Series is a one-dimensional array with labels: think “Series = vector + labels”. The labels are collectively called the index. You create one with pd.Series(data, index=index), where data can be a list, a NumPy array, or a dictionary (whose keys become the index). If you don’t pass an index, it is 0, 1, 2, ....
first_series = pd.Series([2**i for i in range(7)])
print(type(first_series))
print(first_series)s = pd.Series(rng.standard_normal(5), index=['a', 'b', 'c', 'd', 'e'])
print(s)
print('-'*50)
print(s.index)s['a']You can index and slice series like you would numpy arrays/python lists
print(s['b':'d'])s[s > s.mean()]You can sort by index or by value:
print(s.sort_index())
print(s.sort_values())You can also count unique values:
s = pd.Series([0,0,0,1,1,1,2,2,2,2])
s.value_counts()Exercise¶
Consider the series
sof letters in a sentence.What is count of each letter in the sentence, output a series which is sorted by the count
Make a list of the 5 most common letters (not including spaces)
sentence = 'Consider the series s of letters in a sentence.'
s = pd.Series([c for c in sentence])
s## Your code here# Solution
print(s.value_counts())
sc = s[s != ' '].value_counts()
list(sc.index[:5])Data Frames¶
A DataFrame is a 2-dimensional labeled table whose columns can have different types. You can think of it like a spreadsheet, or a dict of Series that share an index. You create one with
df = pd.DataFrame(data, index=index, columns=columns)where data can be a dict of lists, arrays, or Series, a 2D NumPy array, or a list of dicts, and index/columns are the row/column labels. If you leave them out, pandas constructs them from the data.
Documentation: pandas.DataFrame
From a dictionary of lists:
pd.DataFrame({'one': [1., 2., 3., 4.], 'two': [4., 3., 2., 1.]})From a dictionary of Series, the rows are matched by their labels, and missing entries become NaN:
d = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([0, 1, 2, 3], index=['a', 'b', 'c', 'd'])}
pd.DataFrame(d)Adding and Deleting Columns¶
df = pd.DataFrame(d)
df['three'] = df['one'] * df['two'] # a column computed from other columns
df['flag'] = df['one'] > 2 # a boolean column
df# delete a column
three = df.pop('three')
dfIndexing and Selection¶
There are 3 ways to index: [], .loc (by label), and .iloc (by integer position).
| Operation | Syntax | Result |
|---|---|---|
| Select column | df[col] | Series |
| Select columns | df[[col1, col2]] | DataFrame |
| Select row by label | df.loc[label] | Series |
| Select row by integer location | df.iloc[idx] | Series |
| Slice rows | df[5:10] | DataFrame |
| Select rows by boolean | df[mask] | DataFrame |
The same operations work on a Series, restricted to one dimension.
# a data frame whose rows are labeled by dates
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(rng.standard_normal((8, 4)), index=dates, columns=['A', 'B', 'C','D'])
df# slice rows by label
df['2000-01-01': '2000-01-04'].loc selects by label. It accepts a single label, a list of labels, a slice of labels (which includes both endpoints), or a boolean array, and raises a KeyError if a label isn’t found.
# one row, as a Series
df.loc['2000-01-01']df.loc[:, 'A':'C']# all rows, and the columns whose value on 2000-01-01 is positive
df.loc[:, df.loc['2000-01-01'] > 0].iloc selects by integer position. It accepts an integer, a list of integers, a slice (which excludes the endpoint, as in NumPy), or a boolean array.
# rows 0-2
df.iloc[:3]# rows 1-4 and columns 2-3
df.iloc[1:5, 2:4]# lists of rows and columns
df.iloc[[1, 3, 5], [1, 3]]Exercise¶
For the data frame df above, find
Last two rows of columns A and D
The last three rows that satisfy column A > column B
## Your code here# Solution: Last two rows of columns A and D
df.iloc[-2:, [0, 3]]# Solution: The last three rows that satisfy column A > column B
df[df['A'] > df['B']].tail(3)Plotting¶
DataFrames and Series have built-in plotting methods, which use Matplotlib. For example, a histogram of a column:
df = titanic
df.age.hist()
plt.show()or a scatter plot of two columns:
df.plot.scatter(x='age', y='fare', alpha=0.5)
plt.show()Summary Statistics¶
Besides statistics of a single column, like df.age.mean(), you can compute statistics of several (or all) columns. numeric_only=True skips the columns that hold strings, which have no mean.
df.mean(numeric_only=True)You can also compute statistics grouping by category
df.groupby('sex').mean(numeric_only=True)You can count how many records are in each category for categorical variables
df['pclass'].value_counts()df.groupby('sex')['pclass'].value_counts()corr computes the correlation between each pair of numeric columns:
df[['survived', 'pclass', 'age', 'fare']].corr()Table Manipulation¶
You can sort a table by the values in a column (ascending=False sorts from largest to smallest):
df.sort_values(by='age', ascending=False).head()You can also sort by a primary key and a secondary key:
df.sort_values(by=['pclass', 'age']).head()Groups¶
df.groupby(key) (or df.groupby([key1, key2])) splits the rows of a table into groups that share the same value of the key. This is used in the “split-apply-combine” pattern:
Split the data into groups based on some criteria
Apply a function to each group independently
Combine the results

df = pd.DataFrame({'key':['A','B','C','A','B','C','A','B','C'],
'data': [0, 5, 10, 5, 10, 15, 10, 15, 20]})
dfdf.groupby('key').sum()agg applies one or more functions to each group:
df.groupby('key').agg(['sum', 'mean', 'max'])Pivot Tables¶
Say you want the mean age for each sex grouped by class. We can create a pivot table to display the data. aggfunc can be any aggregation, such as "median", "max", or "count".
titanic.pivot_table(values="age", index="sex",
columns="pclass", aggfunc="mean")Binning¶
pd.cut turns a numeric column into a categorical one by sorting the values into bins. Here the bins are , , , and :
age_group = pd.cut(titanic["age"], bins=[0, 12, 18, 60, 100],
labels=["child", "teen", "adult", "senior"])
age_group.value_counts()The binned column can be used like any other, for example to group by it. Here is the fraction of passengers who survived, by age group and sex:
titanic["age_group"] = age_group
# observed=True: only show categories that occur (the default since pandas 3.0)
titanic.pivot_table(values="survived", index="age_group", columns="sex",
aggfunc="mean", observed=True)Merging DataFrames¶
pd.merge joins two tables on a common column, like a join in SQL. The how argument says which keys to keep: "inner" (keys in both tables), "outer" (keys in either), "left", or "right". See the documentation for more options.
left = pd.DataFrame({'key': ['foo', 'bar'], 'lval': [4, 2]})
right = pd.DataFrame({'key': ['bar', 'zoo'], 'rval': [4, 5]})
print(left, right, sep="\n\n")for how in ["inner", "outer", "left", "right"]:
print(f"how={how!r}")
print(pd.merge(left, right, how=how), end="\n\n")Functions¶
df.apply(func, axis=0) applies a function to each column (axis=1: to each row), like the axis argument in NumPy. df.map(func) applies a function to every element (before pandas 2.1 it was called applymap).
df1 = pd.DataFrame(rng.standard_normal((6, 4)), index=list(range(0,12,2)), columns=list('abcd'))
df1# Apply to each column
df1.apply(np.mean, axis=0)# Apply to each row
df1.apply(np.mean, axis=1)# use a lambda function to normalize each column
df1.apply(lambda x: (x - x.mean())/ x.std(), axis = 0)df1.map(np.exp)Bibliography - this notebook used content from some of the following sources: