10 minutes to pandas

This is a short introduction to pandas, geared mainly for new users. You can see more complex recipes in the Cookbookarrow-up-right.

Customarily, we import as follows:

import numpy as np
import pandas as pd

Object creation

See the Data Structure Intro sectionarrow-up-right.

Creating a Seriesarrow-up-right by passing a list of values, letting pandas create a default integer index:

s = pd.Series([1, 3, 5, np.nan, 6, 8])
s

# Out[4]: 
0    1.0
1    3.0
2    5.0
3    NaN
4    6.0
5    8.0
dtype: float64

Creating a DataFramearrow-up-right by passing a NumPy array, with a datetime index and labeled columns:

Creating a DataFrame by passing a dict of objects that can be converted to series-like.

The columns of the resulting DataFrame have different dtypesarrow-up-right.

If you’re using IPython, tab completion for column names (as well as public attributes) is automatically enabled. Here’s a subset of the attributes that will be completed:

As you can see, the columns A, B, C, and D are automatically tab completed. E is there as well; the rest of the attributes have been truncated for brevity.

Viewing data

See the Basics sectionarrow-up-right.

Here is how to view the top and bottom rows of the frame:

Display the index, columns:

DataFrame.to_numpy()arrow-up-right gives a NumPy representation of the underlying data. Note that this can be an expensive operation when your DataFramearrow-up-right has columns with different data types, which comes down to a fundamental difference between pandas and NumPy: NumPy arrays have one dtype for the entire array, while pandas DataFrames have one dtype per column. When you call DataFrame.to_numpy()arrow-up-right, pandas will find the NumPy dtype that can hold all of the dtypes in the DataFrame. This may end up being object, which requires casting every value to a Python object.

For df, our DataFramearrow-up-right of all floating-point values, DataFrame.to_numpy()arrow-up-right is fast and doesn’t require copying data.

For df2, the DataFramearrow-up-right with multiple dtypes, DataFrame.to_numpy()arrow-up-right is relatively expensive.

Note

DataFrame.to_numpy()arrow-up-right does not include the index or column labels in the output.

describe()arrow-up-right shows a quick statistic summary of your data:

Transposing your data:

Sorting by an axis:

Sorting by values:

Selection

Note

While standard Python / Numpy expressions for selecting and setting are intuitive and come in handy for interactive work, for production code, we recommend the optimized pandas data access methods, .at, .iat, .loc and .iloc.

See the indexing documentation Indexing and Selecting Dataarrow-up-right and MultiIndex / Advanced Indexingarrow-up-right.

Getting

Selecting a single column, which yields a Series, equivalent to df.A:

Selecting via [], which slices the rows.

Selection by label

See more in Selection by Labelarrow-up-right.

For getting a cross section using a label:

Selecting on a multi-axis by label:

Showing label slicing, both endpoints are included:

Reduction in the dimensions of the returned object:

For getting a scalar value:

For getting fast access to a scalar (equivalent to the prior method):

Selection by position

See more in Selection by Positionarrow-up-right.

Select via the position of the passed integers:

By integer slices, acting similar to numpy/python:

By lists of integer position locations, similar to the numpy/python style:

For slicing rows explicitly:

For slicing columns explicitly:

For getting a value explicitly:

For getting fast access to a scalar (equivalent to the prior method):

Boolean indexing

Using a single column’s values to select data.

Selecting values from a DataFrame where a boolean condition is met.

Using the isin()arrow-up-right method for filtering:

Setting

Setting a new column automatically aligns the data by the indexes.

Setting values by label:

Setting values by position:

Setting by assigning with a NumPy array:

The result of the prior setting operations.

A where operation with setting.

Missing data

pandas primarily uses the value np.nan to represent missing data. It is by default not included in computations. See the Missing Data sectionarrow-up-right.

Reindexing allows you to change/add/delete the index on a specified axis. This returns a copy of the data.

To drop any rows that have missing data.

Filling missing data.

To get the boolean mask where values are nan.

Operations

See the Basic section on Binary Opsarrow-up-right.

Stats

Operations in general exclude missing data.

Performing a descriptive statistic:

Same operation on the other axis:

Operating with objects that have different dimensionality and need alignment. In addition, pandas automatically broadcasts along the specified dimension.

Apply

Applying functions to the data:

Histogramming

See more at Histogramming and Discretizationarrow-up-right.

String Methods

Series is equipped with a set of string processing methods in the str attribute that make it easy to operate on each element of the array, as in the code snippet below. Note that pattern-matching in str generally uses regular expressionsarrow-up-right by default (and in some cases always uses them). See more at Vectorized String Methodsarrow-up-right.

Merge

Concat

pandas provides various facilities for easily combining together Series and DataFrame objects with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations.

See the Merging sectionarrow-up-right.

Concatenating pandas objects together with concat()arrow-up-right:

Note

Adding a column to a DataFrame is relatively fast. However, adding a row requires a copy, and may be expensive. We recommend passing a pre-built list of records to the DataFrame constructor instead of building a DataFrame by iteratively appending records to it. See Appending to dataframearrow-up-right for more.

Join

SQL style merges. See the Database style joiningarrow-up-right section.

Another example that can be given is:

Grouping

By “group by” we are referring to a process involving one or more of the following steps:

  • Splitting the data into groups based on some criteria

  • Applying a function to each group independently

  • Combining the results into a data structure

See the Grouping sectionarrow-up-right.

Grouping and then applying the sum()arrow-up-right function to the resulting groups.

Grouping by multiple columns forms a hierarchical index, and again we can apply the sum function.

Reshaping

See the sections on Hierarchical Indexingarrow-up-right and Reshapingarrow-up-right.

Stack

The stack()arrow-up-right method “compresses” a level in the DataFrame’s columns.

With a “stacked” DataFrame or Series (having a MultiIndex as the index), the inverse operation of stack()arrow-up-right is unstack()arrow-up-right, which by default unstacks the last level:

Pivot tables

See the section on Pivot Tablesarrow-up-right.

We can produce pivot tables from this data very easily:

Time series

pandas has simple, powerful, and efficient functionality for performing resampling operations during frequency conversion (e.g., converting secondly data into 5-minutely data). This is extremely common in, but not limited to, financial applications. See the Time Series sectionarrow-up-right.

Time zone representation:

Converting to another time zone:

Converting between time span representations:

Converting between period and timestamp enables some convenient arithmetic functions to be used. In the following example, we convert a quarterly frequency with year ending in November to 9am of the end of the month following the quarter end:

Categoricals

pandas can include categorical data in a DataFrame. For full docs, see the categorical introductionarrow-up-right and the API documentationarrow-up-right.

Convert the raw grades to a categorical data type.

Rename the categories to more meaningful names (assigning to Series.cat.categories is inplace!).

Reorder the categories and simultaneously add the missing categories (methods under Series .cat return a new Series by default).

Sorting is per order in the categories, not lexical order.

Grouping by a categorical column also shows empty categories.

Plotting

See the Plottingarrow-up-right docs.

We use the standard convention for referencing the matplotlib API:

../_images/series_plot_basic.png

On a DataFrame, the plot()arrow-up-right method is a convenience to plot all of the columns with labels:

../_images/frame_plot_basic.png

Getting data in/out

CSV

Writing to a csv file.arrow-up-right

Reading from a csv file.arrow-up-right

HDF5

Reading and writing to HDFStoresarrow-up-right.

Writing to a HDF5 Store.

Reading from a HDF5 Store.

Excel

Reading and writing to MS Excelarrow-up-right.

Writing to an excel file.

Reading from an excel file.

Gotchas

If you are attempting to perform an operation you might see an exception like:

See Comparisonsarrow-up-right for an explanation and what to do.

See Gotchasarrow-up-right as well.

Last updated