pandas 0.11.0.dev-9988e5f documentation

Essential basic functionality

Here we discuss a lot of the essential functionality common to the pandas data structures. Here’s how to create some of the objects used in the examples from the previous section:

In [1]: index = date_range('1/1/2000', periods=8)

In [2]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])

In [3]: df = DataFrame(randn(8, 3), index=index,
   ...:                columns=['A', 'B', 'C'])
   ...:

In [4]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
   ...:            major_axis=date_range('1/1/2000', periods=5),
   ...:            minor_axis=['A', 'B', 'C', 'D'])
   ...:

Head and Tail

To view a small sample of a Series or DataFrame object, use the head and tail methods. The default number of elements to display is five, but you may pass a custom number.

In [5]: long_series = Series(randn(1000))

In [6]: long_series.head()
Out[6]: 
0    1.162813
1    0.870161
2    2.792723
3    0.776395
4   -1.181190
dtype: float64

In [7]: long_series.tail(3)
Out[7]: 
997    0.545698
998    0.008194
999    1.452061
dtype: float64

Attributes and the raw ndarray(s)

pandas objects have a number of attributes enabling you to access the metadata

  • shape: gives the axis dimensions of the object, consistent with ndarray
  • Axis labels
    • Series: index (only axis)
    • DataFrame: index (rows) and columns
    • Panel: items, major_axis, and minor_axis

Note, these attributes can be safely assigned to!

In [8]: df[:2]
Out[8]: 
                   A         B         C
2000-01-01 -1.007761  0.561990  0.560802
2000-01-02  0.770819 -0.972052  0.896288

In [9]: df.columns = [x.lower() for x in df.columns]

In [10]: df
Out[10]: 
                   a         b         c
2000-01-01 -1.007761  0.561990  0.560802
2000-01-02  0.770819 -0.972052  0.896288
2000-01-03 -0.718942  0.329576  1.169925
2000-01-04  0.958928 -0.935316 -0.827036
2000-01-05 -1.240656  0.834546 -0.160635
2000-01-06 -3.590370 -1.247926 -1.445820
2000-01-07 -0.042194  0.906744 -0.471145
2000-01-08 -0.256360 -0.098316 -0.770393

To get the actual data inside a data structure, one need only access the values property:

In [11]: s.values
Out[11]: array([-0.5347, -0.0236, -0.9306, -0.2505, -0.1546])

In [12]: df.values
Out[12]: 
array([[-1.0078,  0.562 ,  0.5608],
       [ 0.7708, -0.9721,  0.8963],
       [-0.7189,  0.3296,  1.1699],
       [ 0.9589, -0.9353, -0.827 ],
       [-1.2407,  0.8345, -0.1606],
       [-3.5904, -1.2479, -1.4458],
       [-0.0422,  0.9067, -0.4711],
       [-0.2564, -0.0983, -0.7704]])

In [13]: wp.values
Out[13]: 
array([[[-0.5695,  0.917 ,  0.4495, -0.8452],
        [-0.5009,  0.4569,  0.4477,  0.2638],
        [ 1.3112, -0.0522,  0.508 , -0.7318],
        [-2.1767, -0.5234, -0.2092, -0.1431],
        [-1.0446,  0.5449,  0.0648,  0.4873]],
       [[ 0.0002, -1.3767, -0.7805,  0.6007],
        [-0.8252,  0.4755,  0.7108, -1.3615],
        [-0.4196, -0.701 , -1.3045, -0.2533],
        [ 0.0741, -1.3842, -0.5871, -0.3562],
        [ 1.8788,  1.788 , -1.2921, -0.2672]]])

If a DataFrame or Panel contains homogeneously-typed data, the ndarray can actually be modified in-place, and the changes will be reflected in the data structure. For heterogeneous data (e.g. some of the DataFrame’s columns are not all the same dtype), this will not be the case. The values attribute itself, unlike the axis labels, cannot be assigned to.

Note

When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to accommodate all of the data involved. For example, if strings are involved, the result will be of object dtype. If there are only floats and integers, the resulting array will be of float dtype.

Flexible binary operations

With binary operations between pandas data structures, there are two key points of interest:

  • Broadcasting behavior between higher- (e.g. DataFrame) and lower-dimensional (e.g. Series) objects.
  • Missing data in computations

We will demonstrate how to manage these issues independently, though they can be handled simultaneously.

Matching / broadcasting behavior

DataFrame has the methods add, sub, mul, div and related functions radd, rsub, ... for carrying out binary operations. For broadcasting behavior, Series input is of primary interest. Using these functions, you can use to either match on the index or columns via the axis keyword:

In [14]: d = {'one' : Series(randn(3), index=['a', 'b', 'c']),
   ....:      'two' : Series(randn(4), index=['a', 'b', 'c', 'd']),
   ....:      'three' : Series(randn(3), index=['b', 'c', 'd'])}
   ....:

In [15]: df = DataFrame(d)

In [16]: df
Out[16]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479

In [17]: row = df.ix[1]

In [18]: column = df['two']

In [19]: df.sub(row, axis='columns')
Out[19]: 
        one     three       two
a  0.453509       NaN -1.287417
b  0.000000  0.000000  0.000000
c  1.403018  1.837457 -2.592677
d       NaN  1.305906  0.994857

In [20]: df.sub(row, axis=1)
Out[20]: 
        one     three       two
a  0.453509       NaN -1.287417
b  0.000000  0.000000  0.000000
c  1.403018  1.837457 -2.592677
d       NaN  1.305906  0.994857

In [21]: df.sub(column, axis='index')
Out[21]: 
        one     three  two
a  0.486660       NaN    0
b -1.254266 -2.259826    0
c  2.741429  2.170308    0
d       NaN -1.948777    0

In [22]: df.sub(column, axis=0)
Out[22]: 
        one     three  two
a  0.486660       NaN    0
b -1.254266 -2.259826    0
c  2.741429  2.170308    0
d       NaN -1.948777    0

With Panel, describing the matching behavior is a bit more difficult, so the arithmetic methods instead (and perhaps confusingly?) give you the option to specify the broadcast axis. For example, suppose we wished to demean the data over a particular axis. This can be accomplished by taking the mean over an axis and broadcasting over the same axis:

In [23]: major_mean = wp.mean(axis='major')

In [24]: major_mean
Out[24]: 
      Item1     Item2
A -0.596094  0.141658
B  0.268630 -0.239671
C  0.252154 -0.650685
D -0.193792 -0.327499

In [25]: wp.sub(major_mean, axis='major')
Out[25]: 
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
Minor_axis axis: A to D

And similarly for axis="items" and axis="minor".

Note

I could be convinced to make the axis argument in the DataFrame methods match the broadcasting behavior of Panel. Though it would require a transition period so users can change their code...

Missing data / operations with fill values

In Series and DataFrame (though not yet in Panel), the arithmetic functions have the option of inputting a fill_value, namely a value to substitute when at most one of the values at a location are missing. For example, when adding two DataFrame objects, you may wish to treat NaN as 0 unless both DataFrames are missing that value, in which case the result will be NaN (you can later replace NaN with some other value using fillna if you wish).

In [26]: df
Out[26]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479

In [27]: df2
Out[27]: 
        one     three       two
a  0.133865  1.000000 -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479

In [28]: df + df2
Out[28]: 
        one     three       two
a  0.267730       NaN -0.705590
b -0.639288 -2.650407  1.869244
c  2.166748  1.024507 -3.316109
d       NaN -0.038595  3.858958

In [29]: df.add(df2, fill_value=0)
Out[29]: 
        one     three       two
a  0.267730  1.000000 -0.705590
b -0.639288 -2.650407  1.869244
c  2.166748  1.024507 -3.316109
d       NaN -0.038595  3.858958

Flexible Comparisons

Starting in v0.8, pandas introduced binary comparison methods eq, ne, lt, gt, le, and ge to Series and DataFrame whose behavior is analogous to the binary arithmetic operations described above:

In [30]: df.gt(df2)
Out[30]: 
     one  three    two
a  False  False  False
b  False  False  False
c  False  False  False
d  False  False  False

In [31]: df2.ne(df)
Out[31]: 
     one  three    two
a  False   True  False
b  False  False  False
c  False  False  False
d   True  False  False

Combining overlapping data sets

A problem occasionally arising is the combination of two similar data sets where values in one are preferred over the other. An example would be two data series representing a particular economic indicator where one is considered to be of “higher quality”. However, the lower quality series might extend further back in history or have more complete data coverage. As such, we would like to combine two DataFrame objects where missing values in one DataFrame are conditionally filled with like-labeled values from the other DataFrame. The function implementing this operation is combine_first, which we illustrate:

In [32]: df1 = DataFrame({'A' : [1., np.nan, 3., 5., np.nan],
   ....:                  'B' : [np.nan, 2., 3., np.nan, 6.]})
   ....:

In [33]: df2 = DataFrame({'A' : [5., 2., 4., np.nan, 3., 7.],
   ....:                  'B' : [np.nan, np.nan, 3., 4., 6., 8.]})
   ....:

In [34]: df1
Out[34]: 
    A   B
0   1 NaN
1 NaN   2
2   3   3
3   5 NaN
4 NaN   6

In [35]: df2
Out[35]: 
    A   B
0   5 NaN
1   2 NaN
2   4   3
3 NaN   4
4   3   6
5   7   8

In [36]: df1.combine_first(df2)
Out[36]: 
   A   B
0  1 NaN
1  2   2
2  3   3
3  5   4
4  3   6
5  7   8

General DataFrame Combine

The combine_first method above calls the more general DataFrame method combine. This method takes another DataFrame and a combiner function, aligns the input DataFrame and then passes the combiner function pairs of Series (ie, columns whose names are the same).

So, for instance, to reproduce combine_first as above:

In [37]: combiner = lambda x, y: np.where(isnull(x), y, x)

In [38]: df1.combine(df2, combiner)
Out[38]: 
   A   B
0  1 NaN
1  2   2
2  3   3
3  5   4
4  3   6
5  7   8

Descriptive statistics

A large number of methods for computing descriptive statistics and other related operations on Series, DataFrame, and Panel. Most of these are aggregations (hence producing a lower-dimensional result) like sum, mean, and quantile, but some of them, like cumsum and cumprod, produce an object of the same size. Generally speaking, these methods take an axis argument, just like ndarray.{sum, std, ...}, but the axis can be specified by name or integer:

  • Series: no axis argument needed
  • DataFrame: “index” (axis=0, default), “columns” (axis=1)
  • Panel: “items” (axis=0), “major” (axis=1, default), “minor” (axis=2)

For example:

In [39]: df
Out[39]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479

In [40]: df.mean(0)
Out[40]: 
one      0.299198
three   -0.277416
two      0.213313
dtype: float64

In [41]: df.mean(1)
Out[41]: 
a   -0.109465
b   -0.236742
c   -0.020809
d    0.955091
dtype: float64

All such methods have a skipna option signaling whether to exclude missing data (True by default):

In [42]: df.sum(0, skipna=False)
Out[42]: 
one           NaN
three         NaN
two      0.853252
dtype: float64

In [43]: df.sum(axis=1, skipna=True)
Out[43]: 
a   -0.218930
b   -0.710225
c   -0.062427
d    1.910181
dtype: float64

Combined with the broadcasting / arithmetic behavior, one can describe various statistical procedures, like standardization (rendering data zero mean and standard deviation 1), very concisely:

In [44]: ts_stand = (df - df.mean()) / df.std()

In [45]: ts_stand.std()
Out[45]: 
one      1
three    1
two      1
dtype: float64

In [46]: xs_stand = df.sub(df.mean(1), axis=0).div(df.std(1), axis=0)

In [47]: xs_stand.std(1)
Out[47]: 
a    1
b    1
c    1
d    1
dtype: float64

Note that methods like cumsum and cumprod preserve the location of NA values:

In [48]: df.cumsum()
Out[48]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.185779 -1.325203  0.581827
c  0.897595 -0.812950 -1.076228
d       NaN -0.832247  0.853252

Here is a quick reference summary table of common functions. Each also takes an optional level parameter which applies only if the object has a hierarchical index.

Function Description
count Number of non-null observations
sum Sum of values
mean Mean of values
mad Mean absolute deviation
median Arithmetic median of values
min Minimum
max Maximum
abs Absolute Value
prod Product of values
std Unbiased standard deviation
var Unbiased variance
skew Unbiased skewness (3rd moment)
kurt Unbiased kurtosis (4th moment)
quantile Sample quantile (value at %)
cumsum Cumulative sum
cumprod Cumulative product
cummax Cumulative maximum
cummin Cumulative minimum

Note that by chance some NumPy methods, like mean, std, and sum, will exclude NAs on Series input by default:

In [49]: np.mean(df['one'])
Out[49]: 0.2991983434218195

In [50]: np.mean(df['one'].values)
Out[50]: nan

Series also has a method nunique which will return the number of unique non-null values:

In [51]: series = Series(randn(500))

In [52]: series[20:500] = np.nan

In [53]: series[10:20]  = 5

In [54]: series.nunique()
Out[54]: 11

Summarizing data: describe

There is a convenient describe function which computes a variety of summary statistics about a Series or the columns of a DataFrame (excluding NAs of course):

In [55]: series = Series(randn(1000))

In [56]: series[::2] = np.nan

In [57]: series.describe()
Out[57]: 
count    500.000000
mean      -0.007877
std        0.911618
min       -2.400248
25%       -0.659261
50%        0.023054
75%        0.610466
max        2.548590
dtype: float64

In [58]: frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])

In [59]: frame.ix[::2] = np.nan

In [60]: frame.describe()
Out[60]: 
                a           b           c           d           e
count  500.000000  500.000000  500.000000  500.000000  500.000000
mean     0.027404   -0.062202   -0.085482    0.047872    0.040049
std      1.009556    0.934708    1.020247    0.997085    0.981213
min     -2.820839   -2.629643   -2.907401   -2.678674   -2.439790
25%     -0.699926   -0.660646   -0.746925   -0.646927   -0.580899
50%      0.037665   -0.062781   -0.029457   -0.020508    0.016222
75%      0.708078    0.533449    0.571614    0.769260    0.731781
max      3.169764    2.790953    3.218046    2.766216    2.978102

For a non-numerical Series object, describe will give a simple summary of the number of unique values and most frequently occurring values:

In [61]: s = Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])

In [62]: s.describe()
Out[62]: 
count     9
unique    4
top       a
freq      5
dtype: object

There also is a utility function, value_range which takes a DataFrame and returns a series with the minimum/maximum values in the DataFrame.

Index of Min/Max Values

The idxmin and idxmax functions on Series and DataFrame compute the index labels with the minimum and maximum corresponding values:

In [63]: s1 = Series(randn(5))

In [64]: s1
Out[64]: 
0    0.190816
1    1.570470
2    0.579992
3   -0.570663
4    0.653770
dtype: float64

In [65]: s1.idxmin(), s1.idxmax()
Out[65]: (3, 1)

In [66]: df1 = DataFrame(randn(5,3), columns=['A','B','C'])

In [67]: df1
Out[67]: 
          A         B         C
0  0.010475 -1.886886  0.703759
1  0.567838  0.954075  0.283241
2  0.156650 -1.192535 -1.015856
3  0.413254 -0.530874  0.030274
4 -0.298383 -0.866317 -0.725995

In [68]: df1.idxmin(axis=0)
Out[68]: 
A    4
B    0
C    2
dtype: int64

In [69]: df1.idxmax(axis=1)
Out[69]: 
0    C
1    B
2    A
3    A
4    A
dtype: object

When there are multiple rows (or columns) matching the minimum or maximum value, idxmin and idxmax return the first matching index:

In [70]: df3 = DataFrame([2, 1, 1, 3, np.nan], columns=['A'], index=list('edcba'))

In [71]: df3
Out[71]: 
    A
e   2
d   1
c   1
b   3
a NaN

In [72]: df3['A'].idxmin()
Out[72]: 'd'

Value counts (histogramming)

The value_counts Series method and top-level function computes a histogram of a 1D array of values. It can also be used as a function on regular arrays:

In [73]: data = np.random.randint(0, 7, size=50)

In [74]: data
Out[74]: 
array([2, 3, 1, 4, 0, 4, 0, 2, 3, 0, 3, 3, 4, 3, 0, 3, 6, 6, 0, 6, 2, 0, 0,
       0, 6, 2, 0, 2, 4, 2, 3, 0, 6, 5, 1, 6, 3, 6, 6, 4, 2, 3, 1, 6, 5, 5,
       2, 0, 4, 5])

In [75]: s = Series(data)

In [76]: s.value_counts()
Out[76]: 
0    11
6     9
3     9
2     8
4     6
5     4
1     3
dtype: int64

In [77]: value_counts(data)
Out[77]: 
0    11
6     9
3     9
2     8
4     6
5     4
1     3
dtype: int64

Discretization and quantiling

Continuous values can be discretized using the cut (bins based on values) and qcut (bins based on sample quantiles) functions:

In [78]: arr = np.random.randn(20)

In [79]: factor = cut(arr, 4)

In [80]: factor
Out[80]: 
Categorical: 
array([(-1.841, -0.823], (-0.823, 0.19], (0.19, 1.204], (0.19, 1.204],
       (1.204, 2.218], (-1.841, -0.823], (-1.841, -0.823], (0.19, 1.204],
       (0.19, 1.204], (0.19, 1.204], (-0.823, 0.19], (-1.841, -0.823],
       (-0.823, 0.19], (0.19, 1.204], (-0.823, 0.19], (1.204, 2.218],
       (1.204, 2.218], (-0.823, 0.19], (-1.841, -0.823], (-0.823, 0.19]], dtype=object)
Levels (4): Index([(-1.841, -0.823], (-0.823, 0.19], (0.19, 1.204],
                   (1.204, 2.218]], dtype=object)

In [81]: factor = cut(arr, [-5, -1, 0, 1, 5])

In [82]: factor
Out[82]: 
Categorical: 
array([(-5, -1], (-1, 0], (0, 1], (0, 1], (1, 5], (-5, -1], (-1, 0],
       (0, 1], (1, 5], (0, 1], (-1, 0], (-5, -1], (-1, 0], (0, 1], (-1, 0],
       (1, 5], (1, 5], (-1, 0], (-5, -1], (0, 1]], dtype=object)
Levels (4): Index([(-5, -1], (-1, 0], (0, 1], (1, 5]], dtype=object)

qcut computes sample quantiles. For example, we could slice up some normally distributed data into equal-size quartiles like so:

In [83]: arr = np.random.randn(30)

In [84]: factor = qcut(arr, [0, .25, .5, .75, 1])

In [85]: factor
Out[85]: 
Categorical: 
array([(-0.145, 0.333], (-0.591, -0.145], (0.333, 1.453], (-0.145, 0.333],
       (-0.591, -0.145], [-2.506, -0.591], [-2.506, -0.591],
       (0.333, 1.453], (0.333, 1.453], (-0.145, 0.333], (-0.591, -0.145],
       [-2.506, -0.591], [-2.506, -0.591], [-2.506, -0.591],
       (-0.591, -0.145], (-0.145, 0.333], (0.333, 1.453], (0.333, 1.453],
       (-0.591, -0.145], (0.333, 1.453], [-2.506, -0.591], (-0.145, 0.333],
       (-0.145, 0.333], (0.333, 1.453], (-0.591, -0.145], [-2.506, -0.591],
       (-0.591, -0.145], (-0.145, 0.333], (0.333, 1.453], [-2.506, -0.591]], dtype=object)
Levels (4): Index([[-2.506, -0.591], (-0.591, -0.145], (-0.145, 0.333],
                   (0.333, 1.453]], dtype=object)

In [86]: value_counts(factor)
Out[86]: 
(0.333, 1.453]      8
[-2.506, -0.591]    8
(-0.145, 0.333]     7
(-0.591, -0.145]    7
dtype: int64

Function application

Arbitrary functions can be applied along the axes of a DataFrame or Panel using the apply method, which, like the descriptive statistics methods, take an optional axis argument:

In [87]: df.apply(np.mean)
Out[87]: 
one      0.299198
three   -0.277416
two      0.213313
dtype: float64

In [88]: df.apply(np.mean, axis=1)
Out[88]: 
a   -0.109465
b   -0.236742
c   -0.020809
d    0.955091
dtype: float64

In [89]: df.apply(lambda x: x.max() - x.min())
Out[89]: 
one      1.403018
three    1.837457
two      3.587534
dtype: float64

In [90]: df.apply(np.cumsum)
Out[90]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.185779 -1.325203  0.581827
c  0.897595 -0.812950 -1.076228
d       NaN -0.832247  0.853252

In [91]: df.apply(np.exp)
Out[91]: 
        one     three       two
a  1.143239       NaN  0.702721
b  0.726408  0.265749  2.546251
c  2.954632  1.669048  0.190509
d       NaN  0.980887  6.885923

Depending on the return type of the function passed to apply, the result will either be of lower dimension or the same dimension.

apply combined with some cleverness can be used to answer many questions about a data set. For example, suppose we wanted to extract the date where the maximum value for each column occurred:

In [92]: tsdf = DataFrame(randn(1000, 3), columns=['A', 'B', 'C'],
   ....:                  index=date_range('1/1/2000', periods=1000))
   ....:

In [93]: tsdf.apply(lambda x: x.index[x.dropna().argmax()])
Out[93]: 
A   2000-11-22 00:00:00
B   2001-09-03 00:00:00
C   2002-05-01 00:00:00
dtype: datetime64[ns]

You may also pass additional arguments and keyword arguments to the apply method. For instance, consider the following function you would like to apply:

def subtract_and_divide(x, sub, divide=1):
    return (x - sub) / divide

You may then apply this function as follows:

df.apply(subtract_and_divide, args=(5,), divide=3)

Another useful feature is the ability to pass Series methods to carry out some Series operation on each column or row:

In [94]: tsdf
Out[94]: 
                   A         B         C
2000-01-01  1.162731  0.246389 -0.834775
2000-01-02  1.434571  1.158517  1.031740
2000-01-03 -0.187711 -0.206570  1.435722
2000-01-04       NaN       NaN       NaN
2000-01-05       NaN       NaN       NaN
2000-01-06       NaN       NaN       NaN
2000-01-07       NaN       NaN       NaN
2000-01-08  1.378860 -1.534015  0.464984
2000-01-09  0.494635 -0.344982 -0.178994
2000-01-10  0.369649 -0.345704 -1.047580

In [95]: tsdf.apply(Series.interpolate)
Out[95]: 
                   A         B         C
2000-01-01  1.162731  0.246389 -0.834775
2000-01-02  1.434571  1.158517  1.031740
2000-01-03 -0.187711 -0.206570  1.435722
2000-01-04  0.125603 -0.472059  1.241574
2000-01-05  0.438917 -0.737548  1.047427
2000-01-06  0.752232 -1.003037  0.853279
2000-01-07  1.065546 -1.268526  0.659131
2000-01-08  1.378860 -1.534015  0.464984
2000-01-09  0.494635 -0.344982 -0.178994
2000-01-10  0.369649 -0.345704 -1.047580

Finally, apply takes an argument raw which is False by default, which converts each row or column into a Series before applying the function. When set to True, the passed function will instead receive an ndarray object, which has positive performance implications if you do not need the indexing functionality.

See also

The section on GroupBy demonstrates related, flexible functionality for grouping by some criterion, applying, and combining the results into a Series, DataFrame, etc.

Applying elementwise Python functions

Since not all functions can be vectorized (accept NumPy arrays and return another array or value), the methods applymap on DataFrame and analogously map on Series accept any Python function taking a single value and returning a single value. For example:

In [96]: f = lambda x: len(str(x))

In [97]: df['one'].map(f)
Out[97]: 
a    14
b    15
c    13
d     3
Name: one, dtype: int64

In [98]: df.applymap(f)
Out[98]: 
   one  three  two
a   14      3   15
b   15     14   13
c   13     14   14
d    3     16   13

Series.map has an additional feature which is that it can be used to easily “link” or “map” values defined by a secondary series. This is closely related to merging/joining functionality:

In [99]: s = Series(['six', 'seven', 'six', 'seven', 'six'],
   ....:            index=['a', 'b', 'c', 'd', 'e'])
   ....:

In [100]: t = Series({'six' : 6., 'seven' : 7.})

In [101]: s
Out[101]: 
a      six
b    seven
c      six
d    seven
e      six
dtype: object

In [102]: s.map(t)
Out[102]: 
a    6
b    7
c    6
d    7
e    6
dtype: float64

Reindexing and altering labels

reindex is the fundamental data alignment method in pandas. It is used to implement nearly all other features relying on label-alignment functionality. To reindex means to conform the data to match a given set of labels along a particular axis. This accomplishes several things:

  • Reorders the existing data to match a new set of labels
  • Inserts missing value (NA) markers in label locations where no data for that label existed
  • If specified, fill data for missing labels using logic (highly relevant to working with time series data)

Here is a simple example:

In [103]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])

In [104]: s
Out[104]: 
a    1.143520
b    0.143515
c    1.717025
d   -0.366994
e   -1.255767
dtype: float64

In [105]: s.reindex(['e', 'b', 'f', 'd'])
Out[105]: 
e   -1.255767
b    0.143515
f         NaN
d   -0.366994
dtype: float64

Here, the f label was not contained in the Series and hence appears as NaN in the result.

With a DataFrame, you can simultaneously reindex the index and columns:

In [106]: df
Out[106]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479

In [107]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
Out[107]: 
      three       two       one
c  0.512254 -1.658054  1.083374
f       NaN       NaN       NaN
b -1.325203  0.934622 -0.319644

For convenience, you may utilize the reindex_axis method, which takes the labels and a keyword axis parameter.

Note that the Index objects containing the actual axis labels can be shared between objects. So if we have a Series and a DataFrame, the following can be done:

In [108]: rs = s.reindex(df.index)

In [109]: rs
Out[109]: 
a    1.143520
b    0.143515
c    1.717025
d   -0.366994
dtype: float64

In [110]: rs.index is df.index
Out[110]: True

This means that the reindexed Series’s index is the same Python object as the DataFrame’s index.

See also

Advanced indexing is an even more concise way of doing reindexing.

Note

When writing performance-sensitive code, there is a good reason to spend some time becoming a reindexing ninja: many operations are faster on pre-aligned data. Adding two unaligned DataFrames internally triggers a reindexing step. For exploratory analysis you will hardly notice the difference (because reindex has been heavily optimized), but when CPU cycles matter sprinking a few explicit reindex calls here and there can have an impact.

Reindexing to align with another object

You may wish to take an object and reindex its axes to be labeled the same as another object. While the syntax for this is straightforward albeit verbose, it is a common enough operation that the reindex_like method is available to make this simpler:

In [111]: df
Out[111]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479

In [112]: df2
Out[112]: 
        one       two
a -0.165333  0.005947
b -0.618842  1.293365
c  0.784176 -1.299312

In [113]: df.reindex_like(df2)
Out[113]: 
        one       two
a  0.133865 -0.352795
b -0.319644  0.934622
c  1.083374 -1.658054

Reindexing with reindex_axis

Aligning objects with each other with align

The align method is the fastest way to simultaneously align two objects. It supports a join argument (related to joining and merging):

  • join='outer': take the union of the indexes
  • join='left': use the calling object’s index
  • join='right': use the passed object’s index
  • join='inner': intersect the indexes

It returns a tuple with both of the reindexed Series:

In [114]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])

In [115]: s1 = s[:4]

In [116]: s2 = s[1:]

In [117]: s1.align(s2)
Out[117]: 
(a    0.615848
b   -0.016043
c   -1.447277
d    0.946345
e         NaN
dtype: float64,
 a         NaN
b   -0.016043
c   -1.447277
d    0.946345
e    0.723322
dtype: float64)

In [118]: s1.align(s2, join='inner')
Out[118]: 
(b   -0.016043
c   -1.447277
d    0.946345
dtype: float64,
 b   -0.016043
c   -1.447277
d    0.946345
dtype: float64)

In [119]: s1.align(s2, join='left')
Out[119]: 
(a    0.615848
b   -0.016043
c   -1.447277
d    0.946345
dtype: float64,
 a         NaN
b   -0.016043
c   -1.447277
d    0.946345
dtype: float64)

For DataFrames, the join method will be applied to both the index and the columns by default:

In [120]: df.align(df2, join='inner')
Out[120]: 
(        one       two
a  0.133865 -0.352795
b -0.319644  0.934622
c  1.083374 -1.658054,
         one       two
a -0.165333  0.005947
b -0.618842  1.293365
c  0.784176 -1.299312)

You can also pass an axis option to only align on the specified axis:

In [121]: df.align(df2, join='inner', axis=0)
Out[121]: 
(        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054,
         one       two
a -0.165333  0.005947
b -0.618842  1.293365
c  0.784176 -1.299312)

If you pass a Series to DataFrame.align, you can choose to align both objects either on the DataFrame’s index or columns using the axis argument:

In [122]: df.align(df2.ix[0], axis=1)
Out[122]: 
(        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479,
 one     -0.165333
three         NaN
two      0.005947
Name: a, dtype: float64)

Filling while reindexing

reindex takes an optional parameter method which is a filling method chosen from the following table:

Method Action
pad / ffill Fill values forward
bfill / backfill Fill values backward

Other fill methods could be added, of course, but these are the two most commonly used for time series data. In a way they only make sense for time series or otherwise ordered data, but you may have an application on non-time series data where this sort of “interpolation” logic is the correct thing to do. More sophisticated interpolation of missing values would be an obvious extension.

We illustrate these fill methods on a simple TimeSeries:

In [123]: rng = date_range('1/3/2000', periods=8)

In [124]: ts = Series(randn(8), index=rng)

In [125]: ts2 = ts[[0, 3, 6]]

In [126]: ts
Out[126]: 
2000-01-03    0.990340
2000-01-04   -0.070005
2000-01-05   -0.157860
2000-01-06    0.233077
2000-01-07    0.475897
2000-01-08   -1.029480
2000-01-09   -1.079405
2000-01-10   -0.079334
Freq: D, dtype: float64

In [127]: ts2
Out[127]: 
2000-01-03    0.990340
2000-01-06    0.233077
2000-01-09   -1.079405
dtype: float64

In [128]: ts2.reindex(ts.index)
Out[128]: 
2000-01-03    0.990340
2000-01-04         NaN
2000-01-05         NaN
2000-01-06    0.233077
2000-01-07         NaN
2000-01-08         NaN
2000-01-09   -1.079405
2000-01-10         NaN
Freq: D, dtype: float64

In [129]: ts2.reindex(ts.index, method='ffill')
Out[129]: 
2000-01-03    0.990340
2000-01-04    0.990340
2000-01-05    0.990340
2000-01-06    0.233077
2000-01-07    0.233077
2000-01-08    0.233077
2000-01-09   -1.079405
2000-01-10   -1.079405
Freq: D, dtype: float64

In [130]: ts2.reindex(ts.index, method='bfill')
Out[130]: 
2000-01-03    0.990340
2000-01-04    0.233077
2000-01-05    0.233077
2000-01-06    0.233077
2000-01-07   -1.079405
2000-01-08   -1.079405
2000-01-09   -1.079405
2000-01-10         NaN
Freq: D, dtype: float64

Note the same result could have been achieved using fillna:

In [131]: ts2.reindex(ts.index).fillna(method='ffill')
Out[131]: 
2000-01-03    0.990340
2000-01-04    0.990340
2000-01-05    0.990340
2000-01-06    0.233077
2000-01-07    0.233077
2000-01-08    0.233077
2000-01-09   -1.079405
2000-01-10   -1.079405
Freq: D, dtype: float64

Note these methods generally assume that the indexes are sorted. They may be modified in the future to be a bit more flexible but as time series data is ordered most of the time anyway, this has not been a major priority.

Dropping labels from an axis

A method closely related to reindex is the drop function. It removes a set of labels from an axis:

In [132]: df
Out[132]: 
        one     three       two
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054
d       NaN -0.019298  1.929479

In [133]: df.drop(['a', 'd'], axis=0)
Out[133]: 
        one     three       two
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054

In [134]: df.drop(['one'], axis=1)
Out[134]: 
      three       two
a       NaN -0.352795
b -1.325203  0.934622
c  0.512254 -1.658054
d -0.019298  1.929479

Note that the following also works, but is a bit less obvious / clean:

In [135]: df.reindex(df.index - ['a', 'd'])
Out[135]: 
        one     three       two
b -0.319644 -1.325203  0.934622
c  1.083374  0.512254 -1.658054

Renaming / mapping labels

The rename method allows you to relabel an axis based on some mapping (a dict or Series) or an arbitrary function.

In [136]: s
Out[136]: 
a    0.615848
b   -0.016043
c   -1.447277
d    0.946345
e    0.723322
dtype: float64

In [137]: s.rename(str.upper)
Out[137]: 
A    0.615848
B   -0.016043
C   -1.447277
D    0.946345
E    0.723322
dtype: float64

If you pass a function, it must return a value when called with any of the labels (and must produce a set of unique values). But if you pass a dict or Series, it need only contain a subset of the labels as keys:

In [138]: df.rename(columns={'one' : 'foo', 'two' : 'bar'},
   .....:           index={'a' : 'apple', 'b' : 'banana', 'd' : 'durian'})
   .....:
Out[138]: 
             foo     three       bar
apple   0.133865       NaN -0.352795
banana -0.319644 -1.325203  0.934622
c       1.083374  0.512254 -1.658054
durian       NaN -0.019298  1.929479

The rename method also provides an inplace named parameter that is by default False and copies the underlying data. Pass inplace=True to rename the data in place.

The Panel class has a related rename_axis class which can rename any of its three axes.

Iteration

Because Series is array-like, basic iteration produces the values. Other data structures follow the dict-like convention of iterating over the “keys” of the objects. In short:

  • Series: values
  • DataFrame: column labels
  • Panel: item labels

Thus, for example:

In [139]: for col in df:
   .....:     print col
   .....:
one
three
two

iteritems

Consistent with the dict-like interface, iteritems iterates through key-value pairs:

  • Series: (index, scalar value) pairs
  • DataFrame: (column, Series) pairs
  • Panel: (item, DataFrame) pairs

For example:

In [140]: for item, frame in wp.iteritems():
   .....:     print item
   .....:     print frame
   .....:
Item1
                   A         B         C         D
2000-01-01 -0.569502  0.916952  0.449538 -0.845226
2000-01-02 -0.500946  0.456865  0.447653  0.263834
2000-01-03  1.311241 -0.052172  0.508033 -0.731786
2000-01-04 -2.176710 -0.523424 -0.209228 -0.143088
2000-01-05 -1.044551  0.544929  0.064773  0.487304
Item2
                   A         B         C         D
2000-01-01  0.000200 -1.376720 -0.780456  0.600739
2000-01-02 -0.825227  0.475548  0.710782 -1.361472
2000-01-03 -0.419611 -0.700988 -1.304530 -0.253342
2000-01-04  0.074107 -1.384211 -0.587086 -0.356223
2000-01-05  1.878822  1.788014 -1.292132 -0.267198

iterrows

New in v0.7 is the ability to iterate efficiently through rows of a DataFrame. It returns an iterator yielding each index value along with a Series containing the data in each row:

In [141]: for row_index, row in df2.iterrows():
   .....:     print '%s\n%s' % (row_index, row)
   .....:
a
one   -0.165333
two    0.005947
Name: a, dtype: float64
b
one   -0.618842
two    1.293365
Name: b, dtype: float64
c
one    0.784176
two   -1.299312
Name: c, dtype: float64

For instance, a contrived way to transpose the dataframe would be:

In [142]: df2 = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})

In [143]: print df2
   x  y
0  1  4
1  2  5
2  3  6

In [144]: print df2.T
   0  1  2
x  1  2  3
y  4  5  6

In [145]: df2_t = DataFrame(dict((idx,values) for idx, values in df2.iterrows()))

In [146]: print df2_t
   0  1  2
x  1  2  3
y  4  5  6

itertuples

This method will return an iterator yielding a tuple for each row in the DataFrame. The first element of the tuple will be the row’s corresponding index value, while the remaining values are the row values proper.

For instance,

In [147]: for r in df2.itertuples(): print r
(0, 1, 4)
(1, 2, 5)
(2, 3, 6)

Vectorized string methods

Series is equipped (as of pandas 0.8.1) with a set of string processing methods that make it easy to operate on each element of the array. Perhaps most importantly, these methods exclude missing/NA values automatically. These are accessed via the Series’s str attribute and generally have names matching the equivalent (scalar) build-in string methods:

In [148]: s = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])

In [149]: s.str.lower()
Out[149]: 
0       a
1       b
2       c
3    aaba
4    baca
5     NaN
6    caba
7     dog
8     cat
dtype: object

In [150]: s.str.upper()
Out[150]: 
0       A
1       B
2       C
3    AABA
4    BACA
5     NaN
6    CABA
7     DOG
8     CAT
dtype: object

In [151]: s.str.len()
Out[151]: 
0     1
1     1
2     1
3     4
4     4
5   NaN
6     4
7     3
8     3
dtype: float64

Methods like split return a Series of lists:

In [152]: s2 = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])

In [153]: s2.str.split('_')
Out[153]: 
0    [a, b, c]
1    [c, d, e]
2          NaN
3    [f, g, h]
dtype: object

Elements in the split lists can be accessed using get or [] notation:

In [154]: s2.str.split('_').str.get(1)
Out[154]: 
0      b
1      d
2    NaN
3      g
dtype: object

In [155]: s2.str.split('_').str[1]
Out[155]: 
0      b
1      d
2    NaN
3      g
dtype: object

Methods like replace and findall take regular expressions, too:

In [156]: s3 = Series(['A', 'B', 'C', 'Aaba', 'Baca',
   .....:             '', np.nan, 'CABA', 'dog', 'cat'])
   .....:

In [157]: s3
Out[157]: 
0       A
1       B
2       C
3    Aaba
4    Baca
5        
6     NaN
7    CABA
8     dog
9     cat
dtype: object

In [158]: s3.str.replace('^.a|dog', 'XX-XX ', case=False)
Out[158]: 
0           A
1           B
2           C
3    XX-XX ba
4    XX-XX ca
5            
6         NaN
7    XX-XX BA
8      XX-XX 
9     XX-XX t
dtype: object

Methods like contains, startswith, and endswith takes an extra na arguement so missing values can be considered True or False:

In [159]: s4 = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])

In [160]: s4.str.contains('A', na=False)
Out[160]: 
0     True
1    False
2    False
3     True
4    False
5    False
6     True
7    False
8    False
dtype: bool
Method Description
cat Concatenate strings
split Split strings on delimiter
get Index into each element (retrieve i-th element)
join Join strings in each element of the Series with passed separator
contains Return boolean array if each string contains pattern/regex
replace Replace occurrences of pattern/regex with some other string
repeat Duplicate values (s.str.repeat(3) equivalent to x * 3)
pad Add whitespace to left, right, or both sides of strings
center Equivalent to pad(side='both')
slice Slice each string in the Series
slice_replace Replace slice in each string with passed value
count Count occurrences of pattern
startswith Equivalent to str.startswith(pat) for each element
endswidth Equivalent to str.endswith(pat) for each element
findall Compute list of all occurrences of pattern/regex for each string
match Call re.match on each element, returning matched groups as list
len Compute string lengths
strip Equivalent to str.strip
rstrip Equivalent to str.rstrip
lstrip Equivalent to str.lstrip
lower Equivalent to str.lower
upper Equivalent to str.upper

Sorting by index and value

There are two obvious kinds of sorting that you may be interested in: sorting by label and sorting by actual values. The primary method for sorting axis labels (indexes) across data structures is the sort_index method.

In [161]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
   .....:                          columns=['three', 'two', 'one'])
   .....:

In [162]: unsorted_df.sort_index()
Out[162]: 
      three       two       one
a       NaN -0.352795  0.133865
b -1.325203  0.934622 -0.319644
c  0.512254 -1.658054  1.083374
d -0.019298  1.929479       NaN

In [163]: unsorted_df.sort_index(ascending=False)
Out[163]: 
      three       two       one
d -0.019298  1.929479       NaN
c  0.512254 -1.658054  1.083374
b -1.325203  0.934622 -0.319644
a       NaN -0.352795  0.133865

In [164]: unsorted_df.sort_index(axis=1)
Out[164]: 
        one     three       two
a  0.133865       NaN -0.352795
d       NaN -0.019298  1.929479
c  1.083374  0.512254 -1.658054
b -0.319644 -1.325203  0.934622

DataFrame.sort_index can accept an optional by argument for axis=0 which will use an arbitrary vector or a column name of the DataFrame to determine the sort order:

In [165]: df.sort_index(by='two')
Out[165]: 
        one     three       two
c  1.083374  0.512254 -1.658054
a  0.133865       NaN -0.352795
b -0.319644 -1.325203  0.934622
d       NaN -0.019298  1.929479

The by argument can take a list of column names, e.g.:

In [166]: df = DataFrame({'one':[2,1,1,1],'two':[1,3,2,4],'three':[5,4,3,2]})

In [167]: df[['one', 'two', 'three']].sort_index(by=['one','two'])
Out[167]: 
   one  two  three
2    1    2      3
1    1    3      4
3    1    4      2
0    2    1      5

Series has the method order (analogous to R’s order function) which sorts by value, with special treatment of NA values via the na_last argument:

In [168]: s[2] = np.nan

In [169]: s.order()
Out[169]: 
0       A
3    Aaba
1       B
4    Baca
6    CABA
8     cat
7     dog
2     NaN
5     NaN
dtype: object

In [170]: s.order(na_last=False)
Out[170]: 
2     NaN
5     NaN
0       A
3    Aaba
1       B
4    Baca
6    CABA
8     cat
7     dog
dtype: object

Some other sorting notes / nuances:

  • Series.sort sorts a Series by value in-place. This is to provide compatibility with NumPy methods which expect the ndarray.sort behavior.
  • DataFrame.sort takes a column argument instead of by. This method will likely be deprecated in a future release in favor of just using sort_index.

Copying, type casting

The copy method on pandas objects copies the underlying data (though not the axis indexes, since they are immutable) and returns a new object. Note that it is seldom necessary to copy objects. For example, there are only a handful of ways to alter a DataFrame in-place:

  • Inserting, deleting, or modifying a column
  • Assigning to the index or columns attributes
  • For homogeneous data, directly modifying the values via the values attribute or advanced indexing

To be clear, no pandas methods have the side effect of modifying your data; almost all methods return new objects, leaving the original object untouched. If data is modified, it is because you did so explicitly.

Data can be explicitly cast to a NumPy dtype by using the astype method or alternately passing the dtype keyword argument to the object constructor.

In [171]: df = DataFrame(np.arange(12).reshape((4, 3)))

In [172]: df[0].dtype
Out[172]: dtype('int64')

In [173]: df.astype(float)[0].dtype
Out[173]: dtype('float64')

In [174]: df = DataFrame(np.arange(12).reshape((4, 3)), dtype=float)

In [175]: df[0].dtype
Out[175]: dtype('float64')

Inferring better types for object columns

The convert_objects DataFrame method will attempt to convert dtype=object columns to a better NumPy dtype. Occasionally (after transposing multiple times, for example), a mixed-type DataFrame will end up with everything as dtype=object. This method attempts to fix that:

In [176]: df = DataFrame(randn(6, 3), columns=['a', 'b', 'c'])

In [177]: df['d'] = 'foo'

In [178]: df
Out[178]: 
          a         b         c    d
0  1.031643 -0.189461 -0.437520  foo
1  0.239650  0.056665 -0.950583  foo
2  0.406598 -1.327319 -0.764997  foo
3  0.619450 -0.158757  1.182297  foo
4  0.345184  0.096056  0.724360  foo
5 -2.790083 -0.168660  0.039725  foo

In [179]: df = df.T.T

In [180]: df.dtypes
Out[180]: 
a    object
b    object
c    object
d    object
dtype: object

In [181]: converted = df.convert_objects()

In [182]: converted.dtypes
Out[182]: 
a    float64
b    float64
c    float64
d     object
dtype: object

Pickling and serialization

All pandas objects are equipped with save methods which use Python’s cPickle module to save data structures to disk using the pickle format.

In [183]: df
Out[183]: 
           a           b           c    d
0   1.031643  -0.1894613  -0.4375196  foo
1  0.2396501  0.05666547   -0.950583  foo
2  0.4065984   -1.327319  -0.7649967  foo
3  0.6194499  -0.1587574    1.182297  foo
4   0.345184  0.09605619   0.7243603  foo
5  -2.790083  -0.1686605  0.03972503  foo

In [184]: df.save('foo.pickle')

The load function in the pandas namespace can be used to load any pickled pandas object (or any other pickled object) from file:

In [185]: load('foo.pickle')
Out[185]: 
           a           b           c    d
0   1.031643  -0.1894613  -0.4375196  foo
1  0.2396501  0.05666547   -0.950583  foo
2  0.4065984   -1.327319  -0.7649967  foo
3  0.6194499  -0.1587574    1.182297  foo
4   0.345184  0.09605619   0.7243603  foo
5  -2.790083  -0.1686605  0.03972503  foo

There is also a save function which takes any object as its first argument:

In [186]: save(df, 'foo.pickle')

In [187]: load('foo.pickle')
Out[187]: 
           a           b           c    d
0   1.031643  -0.1894613  -0.4375196  foo
1  0.2396501  0.05666547   -0.950583  foo
2  0.4065984   -1.327319  -0.7649967  foo
3  0.6194499  -0.1587574    1.182297  foo
4   0.345184  0.09605619   0.7243603  foo
5  -2.790083  -0.1686605  0.03972503  foo

Working with package options

Introduced in 0.10.0, pandas supports a new system for working with options. Options have a full “dotted-style”, case-insensitive name (e.g. display.max_rows),

You can get/set options directly as attributes of the top-level options attribute:

In [188]: import pandas as pd

In [189]: pd.options.display.max_rows
Out[189]: 100

In [190]: pd.options.display.max_rows = 999

In [191]: pd.options.display.max_rows
Out[191]: 999

There is also an API composed of 4 relavent functions, available directly from the pandas namespace, and they are:

  • get_option / set_option - get/set the value of a single option.
  • reset_option - reset one or more options to their default value.
  • describe_option - print the descriptions of one or more options.

Note: developers can check out pandas/core/config.py for more info.

but all of the functions above accept a regexp pattern (re.search style) as argument, so passing in a substring will work - as long as it is unambiguous :

In [192]: get_option("display.max_rows")
Out[192]: 999

In [193]: set_option("display.max_rows",101)

In [194]: get_option("display.max_rows")
Out[194]: 101

In [195]: set_option("max_r",102)

In [196]: get_option("display.max_rows")
Out[196]: 102

However, the following will not work because it matches multiple option names, e.g.``display.max_colwidth``, display.max_rows, display.max_columns:

In [197]: try:
   .....:     get_option("display.max_")
   .....: except KeyError as e:
   .....:     print(e)
   .....:
  File "<ipython-input-197-7ccb78c48d28>", line 3
    except KeyError as e:
                         ^
IndentationError: unindent does not match any outer indentation level

Note: Using this form of convenient shorthand may make your code break if new options with similar names are added in future versions.

The docstrings of all the functions document the available options, but you can also get a list of available options and their descriptions with describe_option. When called with no argument describe_option will print out descriptions for all available options.

In [198]: describe_option()
display.chop_threshold: [default: None] [currently: None]
: float or None
        if set to a float value, all float values smaller then the given threshold
        will be displayed as exactly 0 by repr and friends.
display.colheader_justify: [default: right] [currently: right]
: 'left'/'right'
        Controls the justification of column headers. used by DataFrameFormatter.
display.column_space: [default: 12] [currently: 12]No description available.
display.date_dayfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the day first, eg 20/01/2005
display.date_yearfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the year first, eg 2005/01/20
display.encoding: [default: UTF-8] [currently: UTF-8]
: str/unicode
        Defaults to the detected encoding of the console.
        Specifies the encoding to be used for strings returned by to_string,
        these are generally strings meant to be displayed on the console.
display.expand_frame_repr: [default: True] [currently: True]
: boolean
        Whether to print out the full DataFrame repr for wide DataFrames
        across multiple lines.
        If False, the summary representation is shown.
display.float_format: [default: None] [currently: None]
: callable
        The callable should accept a floating point number and return
        a string with the desired format of the number. This is used
        in some places like SeriesFormatter.
        See core.format.EngFormatter for an example.
display.line_width: [default: 80] [currently: 80]
: int
        When printing wide DataFrames, this is the width of each line.
display.max_columns: [default: 20] [currently: 20]
: int
        max_rows and max_columns are used in __repr__() methods to decide if
        to_string() or info() is used to render an object to a string.
        Either one, or both can be set to 0 (experimental). Pandas will figure
        out how big the terminal is and will not display more rows or/and
        columns that can fit on it.
display.max_colwidth: [default: 50] [currently: 50]
: int
        The maximum width in characters of a column in the repr of
        a pandas data structure. When the column overflows, a "..."
        placeholder is embedded in the output.
display.max_info_columns: [default: 100] [currently: 100]
: int
        max_info_columns is used in DataFrame.info method to decide if
        per column information will be printed.
display.max_info_rows: [default: 1000000] [currently: 1000000]
: int or None
        max_info_rows is the maximum number of rows for which a frame will
        perform a null check on its columns when repr'ing To a console.
        The default is 1,000,000 rows. So, if a DataFrame has more
        1,000,000 rows there will be no null check performed on the
        columns and thus the representation will take much less time to
        display in an interactive session. A value of None means always
        perform a null check when repr'ing.
display.max_rows: [default: 100] [currently: 102]
: int
        This sets the maximum number of rows pandas should output when printing
        out various output. For example, this value determines whether the repr()
        for a dataframe prints out fully or just an summary repr.
display.max_seq_items: [default: None] [currently: None]
: int or None
    
        when pretty-printing a long sequence, no more then `max_seq_items`
        will be printed. If items are ommitted, they will be denoted by the addition
        of "..." to the resulting string.
    
        If set to None, the number of items to be printed is unlimited.
display.multi_sparse: [default: True] [currently: True]
: boolean
        "sparsify" MultiIndex display (don't display repeated
        elements in outer levels within groups)
display.notebook_repr_html: [default: True] [currently: True]
: boolean
        When True, IPython notebook will use html representation for
        pandas objects (if it is available).
display.pprint_nest_depth: [default: 3] [currently: 3]
: int
        Controls the number of nested levels to process when pretty-printing
display.precision: [default: 7] [currently: 7]
: int
        Floating point output precision (number of significant digits). This is
        only a suggestion
mode.sim_interactive: [default: False] [currently: False]
: boolean
        Whether to simulate interactive mode for purposes of testing
mode.use_inf_as_null: [default: False] [currently: False]
: boolean
        True means treat None, NaN, INF, -INF as null (old way),
        False means None and NaN are null, but INF, -INF are not null
        (new way).

or you can get the description for just the options that match the regexp you pass in:

In [199]: describe_option("date")
display.date_dayfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the day first, eg 20/01/2005
display.date_yearfirst: [default: False] [currently: False]
: boolean
        When True, prints and parses dates with the year first, eg 2005/01/20

All options also have a default value, and you can use the reset_option to do just that:

In [200]: get_option("display.max_rows")
Out[200]: 100

In [201]: set_option("display.max_rows",999)

In [202]: get_option("display.max_rows")
Out[202]: 999

In [203]: reset_option("display.max_rows")

In [204]: get_option("display.max_rows")
Out[204]: 100

and you also set multiple options at once:

In [205]: reset_option("^display\.")

Console Output Formatting

Note: set_printoptions/ reset_printoptions are now deprecated (but functioning), and both, as well as set_eng_float_format, use the options API behind the scenes. The corresponding options now live under “print.XYZ”, and you can set them directly with get/set_option.

Use the set_eng_float_format function in the pandas.core.common module to alter the floating-point formatting of pandas objects to produce a particular format.

For instance:

In [206]: set_eng_float_format(accuracy=3, use_eng_prefix=True)

In [207]: df['a']/1.e3
Out[207]: 
0      1.032m
1    239.650u
2    406.598u
3    619.450u
4    345.184u
5     -2.790m
Name: a, dtype: object

In [208]: df['a']/1.e6
Out[208]: 
0      1.032u
1    239.650n
2    406.598n
3    619.450n
4    345.184n
5     -2.790u
Name: a, dtype: object

The set_printoptions function has a number of options for controlling how floating point numbers are formatted (using hte precision argument) in the console and . The max_rows and max_columns control how many rows and columns of DataFrame objects are shown by default. If max_columns is set to 0 (the default, in fact), the library will attempt to fit the DataFrame’s string representation into the current terminal width, and defaulting to the summary view otherwise.