Cookbook

This is a repository for short and sweet examples and links for useful pandas recipes. We encourage users to add to this documentation.

Adding interesting links and/or inline examples to this section is a great First Pull Request.

Simplified, condensed, new-user friendly, in-line examples have been inserted where possible to augment the Stack-Overflow and GitHub links. Many of the links contain expanded information, above what the in-line examples offer.

Pandas (pd) and Numpy (np) are the only two abbreviated imported modules. The rest are kept explicitly imported for newer users.

These examples are written for Python 3. Minor tweaks might be necessary for earlier python versions.

Idioms

These are some neat pandas idioms

if-then/if-then-else on one column, and assignment to another one or more columns:arrow-up-right

In [1]: df = pd.DataFrame({'AAA': [4, 5, 6, 7],
   ...:                    'BBB': [10, 20, 30, 40],
   ...:                    'CCC': [100, 50, -30, -50]})
   ...: 

In [2]: df
Out[2]: 
   AAA  BBB  CCC
0    4   10  100
1    5   20   50
2    6   30  -30
3    7   40  -50

if-then…

An if-then on one column

An if-then with assignment to 2 columns:

Add another line with different logic, to do the -else

Or use pandas where after you’ve set up a mask

if-then-else using numpy’s where()arrow-up-right

Splitting

Split a frame with a boolean criterionarrow-up-right

Building criteria

Select with multi-column criteriaarrow-up-right

…and (without assignment returns a Series)

…or (without assignment returns a Series)

…or (with assignment modifies the DataFrame.)

Select rows with data closest to certain value using argsortarrow-up-right

Dynamically reduce a list of criteria using a binary operatorsarrow-up-right

One could hard code:

…Or it can be done with a list of dynamically built criteria

Selection

DataFrames

The indexingarrow-up-right docs.

Using both row labels and value conditionalsarrow-up-right

Use loc for label-oriented slicing and iloc positional slicingarrow-up-right

There are 2 explicit slicing methods, with a third general case

  1. Positional-oriented (Python slicing style : exclusive of end)

  2. Label-oriented (Non-Python slicing style : inclusive of end)

  3. General (Either slicing style : depends on if the slice contains labels or positions)

Ambiguity arises when an index consists of integers with a non-zero start or non-unit increment.

Using inverse operator (~) to take the complement of a maskarrow-up-right

New columns

Efficiently and dynamically creating new columns using applymaparrow-up-right

Keep other columns when using min() with groupbyarrow-up-right

Method 1 : idxmin() to get the index of the minimums

Method 2 : sort then take first of each

Notice the same results, with the exception of the index.

MultiIndexing

The multindexingarrow-up-right docs.

Creating a MultiIndex from a labeled framearrow-up-right

Arithmetic

Performing arithmetic with a MultiIndex that needs broadcastingarrow-up-right

Slicing

Slicing a MultiIndex with xsarrow-up-right

To take the cross section of the 1st level and 1st axis the index:

…and now the 2nd level of the 1st axis.

Slicing a MultiIndex with xs, method #2arrow-up-right

Setting portions of a MultiIndex with xsarrow-up-right

Sorting

Sort by specific column or an ordered list of columns, with a MultiIndexarrow-up-right

Partial selection, the need for sortedness;arrow-up-right

Levels

Prepending a level to a multiindexarrow-up-right

Flatten Hierarchical columnsarrow-up-right

Missing data

The missing dataarrow-up-right docs.

Fill forward a reversed timeseries

cumsum reset at NaN valuesarrow-up-right

Replace

Using replace with backrefsarrow-up-right

Grouping

The groupingarrow-up-right docs.

Basic grouping with applyarrow-up-right

Unlike agg, apply’s callable is passed a sub-DataFrame which gives you access to all the columns

Using get_grouparrow-up-right

Apply to different items in a grouparrow-up-right

Expanding applyarrow-up-right

Replacing some values with mean of the rest of a grouparrow-up-right

Sort groups by aggregated dataarrow-up-right

Create multiple aggregated columnsarrow-up-right

Create a value counts column and reassign back to the DataFramearrow-up-right

Shift groups of the values in a column based on the indexarrow-up-right

Select row with maximum value from each grouparrow-up-right

Grouping like Python’s itertools.groupbyarrow-up-right

Expanding data

Alignment and to-datearrow-up-right

Rolling Computation window based on values instead of countsarrow-up-right

Rolling Mean by Time Intervalarrow-up-right

Splitting

Splitting a framearrow-up-right

Create a list of dataframes, split using a delineation based on logic included in rows.

Pivot

The Pivotarrow-up-right docs.

Partial sums and subtotalsarrow-up-right

Frequency table like plyr in Rarrow-up-right

Plot pandas DataFrame with year over year dataarrow-up-right

To create year and month cross tabulation:

Apply

Rolling apply to organize - Turning embedded lists into a MultiIndex framearrow-up-right

Rolling apply with a DataFrame returning a Seriesarrow-up-right

Rolling Apply to multiple columns where function calculates a Series before a Scalar from the Series is returned

Rolling apply with a DataFrame returning a Scalararrow-up-right

Rolling Apply to multiple columns where function returns a Scalar (Volume Weighted Average Price)

Timeseries

Between timesarrow-up-right

Using indexer between timearrow-up-right

Constructing a datetime range that excludes weekends and includes only certain timesarrow-up-right

Vectorized Lookuparrow-up-right

Aggregation and plotting time seriesarrow-up-right

Turn a matrix with hours in columns and days in rows into a continuous row sequence in the form of a time series. How to rearrange a Python pandas DataFrame?arrow-up-right

Dealing with duplicates when reindexing a timeseries to a specified frequencyarrow-up-right

Calculate the first day of the month for each entry in a DatetimeIndex

Resampling

The Resamplearrow-up-right docs.

Using Grouper instead of TimeGrouper for time grouping of valuesarrow-up-right

Time grouping with some missing valuesarrow-up-right

Valid frequency arguments to Grouperarrow-up-right

Grouping using a MultiIndexarrow-up-right

Using TimeGrouper and another grouping to create subgroups, then apply a custom functionarrow-up-right

Resampling with custom periodsarrow-up-right

Resample intraday frame without adding new daysarrow-up-right

Resample minute dataarrow-up-right

Resample with groupbyarrow-up-right

Merge

The Concatarrow-up-right docs. The Joinarrow-up-right docs.

Append two dataframes with overlapping index (emulate R rbind)arrow-up-right

Depending on df construction, ignore_index may be needed

Self Join of a DataFramearrow-up-right

How to set the index and joinarrow-up-right

KDB like asof joinarrow-up-right

Join with a criteria based on the valuesarrow-up-right

Using searchsorted to merge based on values inside a rangearrow-up-right

Plotting

The Plottingarrow-up-right docs.

Make Matplotlib look like Rarrow-up-right

Setting x-axis major and minor labelsarrow-up-right

Plotting multiple charts in an ipython notebookarrow-up-right

Creating a multi-line plotarrow-up-right

Plotting a heatmaparrow-up-right

Annotate a time-series plotarrow-up-right

Annotate a time-series plot #2arrow-up-right

Generate Embedded plots in excel files using Pandas, Vincent and xlsxwriterarrow-up-right

Boxplot for each quartile of a stratifying variablearrow-up-right

../_images/quartile_boxplot.png

Data In/Out

Performance comparison of SQL vs HDF5arrow-up-right

CSV

The CSVarrow-up-right docs

read_csv in actionarrow-up-right

appending to a csvarrow-up-right

Reading a csv chunk-by-chunkarrow-up-right

Reading only certain rows of a csv chunk-by-chunkarrow-up-right

Reading the first few lines of a framearrow-up-right

Reading a file that is compressed but not by gzip/bz2 (the native compressed formats which read_csv understands). This example shows a WinZipped file, but is a general application of opening the file within a context manager and using that handle to read. See herearrow-up-right

Inferring dtypes from a filearrow-up-right

Dealing with bad linesarrow-up-right

Dealing with bad lines IIarrow-up-right

Reading CSV with Unix timestamps and converting to local timezonearrow-up-right

Write a multi-row index CSV without writing duplicatesarrow-up-right

Reading multiple files to create a single DataFrame

The best way to combine multiple files into a single DataFrame is to read the individual frames one by one, put all of the individual frames into a list, and then combine the frames in the list using pd.concat():

You can use the same approach to read all files matching a pattern. Here is an example using glob:

Finally, this strategy will work with the other pd.read_*(...) functions described in the io docsarrow-up-right.

Parsing date components in multi-columns

Parsing date components in multi-columns is faster with a format

Skip row between header and data

Option 1: pass rows explicitly to skip rows

Option 2: read column names and then data

SQL

The SQLarrow-up-right docs

Reading from databases with SQLarrow-up-right

Excel

The Excelarrow-up-right docs

Reading from a filelike handlearrow-up-right

Modifying formatting in XlsxWriter outputarrow-up-right

HTML

Reading HTML tables from a server that cannot handle the default request headerarrow-up-right

HDFStore

The HDFStoresarrow-up-right docs

Simple queries with a Timestamp Indexarrow-up-right

Managing heterogeneous data using a linked multiple table hierarchyarrow-up-right

Merging on-disk tables with millions of rowsarrow-up-right

Avoiding inconsistencies when writing to a store from multiple processes/threadsarrow-up-right

De-duplicating a large store by chunks, essentially a recursive reduction operation. Shows a function for taking in data from csv file and creating a store by chunks, with date parsing as well. See herearrow-up-right

Creating a store chunk-by-chunk from a csv filearrow-up-right

Appending to a store, while creating a unique indexarrow-up-right

Large Data work flowsarrow-up-right

Reading in a sequence of files, then providing a global unique index to a store while appendingarrow-up-right

Groupby on a HDFStore with low group densityarrow-up-right

Groupby on a HDFStore with high group densityarrow-up-right

Hierarchical queries on a HDFStorearrow-up-right

Counting with a HDFStorearrow-up-right

Troubleshoot HDFStore exceptionsarrow-up-right

Setting min_itemsize with stringsarrow-up-right

Using ptrepack to create a completely-sorted-index on a storearrow-up-right

Storing Attributes to a group node

Binary files

pandas readily accepts NumPy record arrays, if you need to read in a binary file consisting of an array of C structs. For example, given this C program in a file called main.c compiled with gcc main.c -std=gnu99 on a 64-bit machine,

the following Python code will read the binary file 'binary.dat' into a pandas DataFrame, where each element of the struct corresponds to a column in the frame:

Note

The offsets of the structure elements may be different depending on the architecture of the machine on which the file was created. Using a raw binary file format like this for general data storage is not recommended, as it is not cross platform. We recommended either HDF5 or parquet, both of which are supported by pandas’ IO facilities.

Computation

Numerical integration (sample-based) of a time seriesarrow-up-right

Correlation

Often it’s useful to obtain the lower (or upper) triangular form of a correlation matrix calculated from DataFrame.corr()arrow-up-right. This can be achieved by passing a boolean mask to where as follows:

The method argument within DataFrame.corr can accept a callable in addition to the named correlation types. Here we compute the distance correlationarrow-up-right matrix for a DataFrame object.

Timedeltas

The Timedeltasarrow-up-right docs.

Using timedeltasarrow-up-right

Adding and subtracting deltas and datesarrow-up-right

Another examplearrow-up-right

Values can be set to NaT using np.nan, similar to datetime

Aliasing axis names

To globally provide aliases for axis names, one can define these 2 functions:

Creating example data

To create a dataframe from every combination of some given values, like R’s expand.grid() function, we can create a dict where the keys are column names and the values are lists of the data values:

Reference : https://pandas.pydata.org/pandas-docs/stable/user_guide/cookbook.htmlarrow-up-right

Last updated