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

Open in Colab

Pandas is a Python package for tabular data.

You may need to install pandas first

(pycourse) $ conda install pandas

Overview

Pandas provides two objects:

NameDimensionsDescription
pd.Series1labeled array
pd.DataFrame2labeled 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.

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

Column titles can also be used as attributes:

Pandas DataFrames and Series have a variety of built-in methods to examine data

You can display a variety of statistics using describe(). Note that NaN values are simply ignored.

depending on the type of data held in the series, describe has different functionality.

You can find some more discussion in the Pandas tutorial here

Selecting Subsets of DataFrames

You can select multiple columns

If you want to select certain rows, using some sort of criteria, you can create a series of booleans

We see that we only have 305 rows now

If you just want to access specific rows, you can use iloc

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:

dropna drops the rows with missing values (here, only missing values in the age column count), and fillna replaces missing values with something else.

Exercise

Replace the missing values in the age column of the Titanic data set by the mean age, using fillna.

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

You can index and slice series like you would numpy arrays/python lists

You can sort by index or by value:

You can also count unique values:

Exercise

  • Consider the series s of 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)

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:

From a dictionary of Series, the rows are matched by their labels, and missing entries become NaN:

Adding and Deleting Columns

Indexing and Selection

There are 3 ways to index: [], .loc (by label), and .iloc (by integer position).

OperationSyntaxResult
Select columndf[col]Series
Select columnsdf[[col1, col2]]DataFrame
Select row by labeldf.loc[label]Series
Select row by integer locationdf.iloc[idx]Series
Slice rowsdf[5:10]DataFrame
Select rows by booleandf[mask]DataFrame

The same operations work on a Series, restricted to one dimension.

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

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

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

Plotting

DataFrames and Series have built-in plotting methods, which use Matplotlib. For example, a histogram of a column:

or a scatter plot of two columns:

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.

You can also compute statistics grouping by category

You can count how many records are in each category for categorical variables

corr computes the correlation between each pair of numeric columns:

Table Manipulation

You can sort a table by the values in a column (ascending=False sorts from largest to smallest):

You can also sort by a primary key and a secondary key:

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

image

agg applies one or more functions to each group:

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

Binning

pd.cut turns a numeric column into a categorical one by sorting the values into bins. Here the bins are (0,12](0, 12], (12,18](12, 18], (18,60](18, 60], and (60,100](60, 100]:

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:

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.

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

Bibliography - this notebook used content from some of the following sources: