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

Customarily, we import as follows:

Object creation

See the Data Structure Intro section.

Creating a Series by passing a list of values, letting pandas create a default integer index:

Creating a DataFrame 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 dtypes.

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

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

Display the index, columns:

DataFrame.to_numpy() gives a NumPy representation of the underlying data. Note that this can be an expensive operation when your DataFrame 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(), 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 DataFrame of all floating-point values, DataFrame.to_numpy() is fast and doesn’t require copying data.

For df2, the DataFrame with multiple dtypes, DataFrame.to_numpy() is relatively expensive.

Note

DataFrame.to_numpy() does not include the index or column labels in the output.

describe() 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 Data and MultiIndex / Advanced Indexing.

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

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

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

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

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

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

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 expressions by default (and in some cases always uses them). See more at Vectorized String Methods.

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

Concatenating pandas objects together with concat():

Join

SQL style merges. See the Database style joining section.

Another example that can be given is:

Append

Append rows to a dataframe. See the Appending section.

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

Grouping and then applying the sum() 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 Indexing and Reshaping.

Stack

The stack() 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() is unstack(), which by default unstacks the last level:

Pivot tables

See the section on Pivot Tables.

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

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 introduction and the API documentation.

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

../_images/series_plot_basic.png

On a DataFrame, the plot() 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.

Reading from a csv file.

HDF5

Reading and writing to HDFStores.

Writing to a HDF5 Store.

Reading from a HDF5 Store.

Excel

Reading and writing to MS Excel.

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 Comparisons for an explanation and what to do.

See Gotchas as well.