pandas 0.8.0 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   -0.239227
1    1.217244
2   -0.510938
3   -0.776013
4   -0.067052

In [7]: long_series.tail(3)
Out[7]: 
997   -0.285674
998    1.180547
999   -2.514849

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.929846 -1.073400  1.709955
2000-01-02  1.382386  0.979592  0.203268

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

In [10]: df
Out[10]: 
                   a         b         c
2000-01-01 -1.929846 -1.073400  1.709955
2000-01-02  1.382386  0.979592  0.203268
2000-01-03 -0.577860  0.454677 -0.416935
2000-01-04 -0.831842  1.585026 -2.044555
2000-01-05  0.450603  1.298613 -0.638553
2000-01-06  1.315376  0.704146  1.638736
2000-01-07 -0.947297 -0.536153 -2.896066
2000-01-08  1.002695 -0.254966 -0.014800

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

In [11]: s.values
Out[11]: array([-1.0313,  0.0806, -0.1511,  0.2695, -1.8477])

In [12]: df.values
Out[12]: 
array([[-1.9298, -1.0734,  1.71  ],
       [ 1.3824,  0.9796,  0.2033],
       [-0.5779,  0.4547, -0.4169],
       [-0.8318,  1.585 , -2.0446],
       [ 0.4506,  1.2986, -0.6386],
       [ 1.3154,  0.7041,  1.6387],
       [-0.9473, -0.5362, -2.8961],
       [ 1.0027, -0.255 , -0.0148]])

In [13]: wp.values
Out[13]: 
array([[[ 0.4955,  0.8345,  0.9478,  0.8532],
        [-0.1208,  0.5038, -1.0334,  0.5589],
        [-2.1464, -2.2224, -0.4394, -0.1963],
        [-0.2715, -0.4547,  0.677 , -0.5776],
        [-0.1613, -0.1757, -0.1543, -1.1215]],
       [[ 0.7851,  0.0999,  0.1639, -0.2401],
        [ 0.1923,  0.9876, -0.2078,  1.5908],
        [-1.2695, -0.8448,  0.4097,  0.5735],
        [ 0.7954,  0.557 , -0.8282,  0.1817],
        [-0.3488, -0.1513,  1.39  ,  0.9412]]])

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]: df
Out[14]: 
        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689

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

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

In [17]: df.sub(row, axis='columns')
Out[17]: 
        one     three       two
a  0.599518       NaN -2.005110
b  0.000000  0.000000  0.000000
c -1.428609 -1.374858 -1.052341
d       NaN  1.330384  0.180556

In [18]: df.sub(row, axis=1)
Out[18]: 
        one     three       two
a  0.599518       NaN -2.005110
b  0.000000  0.000000  0.000000
c -1.428609 -1.374858 -1.052341
d       NaN  1.330384  0.180556

In [19]: df.sub(column, axis='index')
Out[19]: 
        one     three  two
a  2.446124       NaN    0
b -0.158504 -0.461612    0
c -0.534772 -0.784129    0
d       NaN  0.688216    0

In [20]: df.sub(column, axis=0)
Out[20]: 
        one     three  two
a  2.446124       NaN    0
b -0.158504 -0.461612    0
c -0.534772 -0.784129    0
d       NaN  0.688216    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 [21]: major_mean = wp.mean(axis='major')

In [22]: major_mean
Out[22]: 
      Item1     Item2
A -0.440882  0.030909
B -0.302883  0.129680
C -0.000464  0.185520
D -0.096696  0.609421

In [23]: wp.sub(major_mean, axis='major')
Out[23]: 
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 5 (major) x 4 (minor)
Items: Item1 to Item2
Major axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
Minor 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 [24]: df
Out[24]: 
        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689

In [25]: df2
Out[25]: 
        one     three       two
a  0.956147  1.000000 -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689

In [26]: df + df2
Out[26]: 
        one     three       two
a  1.912294       NaN -2.979953
b  0.713259  0.107043  1.030267
c -2.143959 -2.642673 -1.074415
d       NaN  2.767811  1.391379

In [27]: df.add(df2, fill_value=0)
Out[27]: 
        one     three       two
a  1.912294  1.000000 -2.979953
b  0.713259  0.107043  1.030267
c -2.143959 -2.642673 -1.074415
d       NaN  2.767811  1.391379

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 [28]: df.gt(df2)
Out[28]: 
     one  three    two
a  False  False  False
b  False  False  False
c  False  False  False
d  False  False  False

In [29]: df2.ne(df)
Out[29]: 
     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 [30]: df1 = DataFrame({'A' : [1., np.nan, 3., 5., np.nan],
   ....:                  'B' : [np.nan, 2., 3., np.nan, 6.]})
   ....:

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

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

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

In [34]: df1.combine_first(df2)
Out[34]: 
   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 [35]: combiner = lambda x, y: np.where(isnull(x), y, x)

In [36]: df1.combine(df2, combiner)
Out[36]: 
   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 [37]: df
Out[37]: 
        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689

In [38]: df.mean(0)
Out[38]: 
one      0.080266
three    0.038697
two     -0.204090

In [39]: df.mean(1)
Out[39]: 
a   -0.266915
b    0.308428
c   -0.976841
d    1.039797

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

In [40]: df.sum(0, skipna=False)
Out[40]: 
one           NaN
three         NaN
two     -0.816361

In [41]: df.sum(axis=1, skipna=True)
Out[41]: 
a   -0.533830
b    0.925285
c   -2.930523
d    2.079595

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 [42]: ts_stand = (df - df.mean()) / df.std()

In [43]: ts_stand.std()
Out[43]: 
one      1
three    1
two      1

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

In [45]: xs_stand.std(1)
Out[45]: 
a    1
b    1
c    1
d    1

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

In [46]: df.cumsum()
Out[46]: 
        one     three       two
a  0.956147       NaN -1.489977
b  1.312776  0.053522 -0.974843
c  0.240797 -1.267815 -1.512050
d       NaN  0.116091 -0.816361

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 [47]: np.mean(df['one'])
Out[47]: 0.080265716524880792

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

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

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

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

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

In [52]: series.nunique()
Out[52]: 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 [53]: series = Series(randn(1000))

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

In [55]: series.describe()
Out[55]: 
count    500.000000
mean       0.026113
std        1.004548
min       -3.216207
25%       -0.665634
50%       -0.038008
75%        0.733741
max        3.234016

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

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

In [58]: frame.describe()
Out[58]: 
                a           b           c           d           e
count  500.000000  500.000000  500.000000  500.000000  500.000000
mean    -0.027293    0.025254    0.035397    0.013762    0.027456
std      0.998836    1.029592    0.947577    1.028132    0.898655
min     -4.516724   -3.151669   -2.682313   -2.856699   -2.778670
25%     -0.650868   -0.715179   -0.581749   -0.726200   -0.502217
50%     -0.112908    0.052980   -0.003960    0.069510   -0.004934
75%      0.591727    0.696976    0.637531    0.653748    0.627489
max      2.781212    3.108559    3.208061    2.815612    2.862146

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

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

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

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 [61]: s1 = Series(randn(5))

In [62]: s1
Out[62]: 
0   -0.995386
1   -0.845334
2    1.211669
3    0.050416
4    0.583484

In [63]: s1.idxmin(), s1.idxmax()
Out[63]: (0, 2)

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

In [65]: df1
Out[65]: 
          A         B         C
0 -0.017543 -1.825033  0.031052
1  0.616602 -0.296397  0.511745
2 -1.202242 -0.330456 -0.697009
3 -0.771030 -1.150410  1.455635
4 -0.425367 -1.087670 -0.454197

In [66]: df1.idxmin(axis=0)
Out[66]: 
A    2
B    0
C    2

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

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 [68]: data = np.random.randint(0, 7, size=50)

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

In [70]: s = Series(data)

In [71]: s.value_counts()
Out[71]: 
4    13
0    10
6     7
1     7
5     6
3     5
2     2

In [72]: value_counts(data)
Out[72]: 
4    13
0    10
6     7
1     7
5     6
3     5
2     2

Discretization and quantiling

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

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

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

In [75]: factor
Out[75]: 
Categorical: 
array([(-0.0666, 0.838], (-0.971, -0.0666], (-0.0666, 0.838],
       (-1.879, -0.971], (-1.879, -0.971], (-0.0666, 0.838],
       (-0.0666, 0.838], (0.838, 1.742], (-1.879, -0.971], (0.838, 1.742],
       (-0.0666, 0.838], (-0.0666, 0.838], (-0.971, -0.0666],
       (0.838, 1.742], (0.838, 1.742], (-1.879, -0.971], (-0.971, -0.0666],
       (0.838, 1.742], (0.838, 1.742], (-0.971, -0.0666]], dtype=object)
Levels (4): Index([(-1.879, -0.971], (-0.971, -0.0666],
                   (-0.0666, 0.838], (0.838, 1.742]], dtype=object)

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

In [77]: factor
Out[77]: 
Categorical: 
array([(0, 1], (-1, 0], (0, 1], (-5, -1], (-5, -1], (0, 1], (0, 1], (1, 5],
       (-5, -1], (1, 5], (0, 1], (0, 1], (-1, 0], (1, 5], (1, 5], (-5, -1],
       (-1, 0], (1, 5], (0, 1], (-1, 0]], 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 [78]: arr = np.random.randn(30)

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

In [80]: factor
Out[80]: 
Categorical: 
array([(0.76, 2.182], (0.76, 2.182], (0.0663, 0.76], (0.76, 2.182],
       [-1.866, -0.607], [-1.866, -0.607], (0.0663, 0.76],
       (-0.607, 0.0663], (0.76, 2.182], (0.0663, 0.76], (-0.607, 0.0663],
       (-0.607, 0.0663], (0.76, 2.182], (-0.607, 0.0663], (-0.607, 0.0663],
       [-1.866, -0.607], [-1.866, -0.607], (-0.607, 0.0663], (0.76, 2.182],
       [-1.866, -0.607], (-0.607, 0.0663], (0.0663, 0.76], (0.0663, 0.76],
       (0.76, 2.182], [-1.866, -0.607], [-1.866, -0.607], (0.0663, 0.76],
       (0.0663, 0.76], (0.76, 2.182], [-1.866, -0.607]], dtype=object)
Levels (4): Index([[-1.866, -0.607], (-0.607, 0.0663], (0.0663, 0.76],
                   (0.76, 2.182]], dtype=object)

In [81]: value_counts(factor)
Out[81]: 
[-1.866, -0.607]    8
(0.76, 2.182]       8
(0.0663, 0.76]      7
(-0.607, 0.0663]    7

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 [82]: df.apply(np.mean)
Out[82]: 
one      0.080266
three    0.038697
two     -0.204090

In [83]: df.apply(np.mean, axis=1)
Out[83]: 
a   -0.266915
b    0.308428
c   -0.976841
d    1.039797

In [84]: df.apply(lambda x: x.max() - x.min())
Out[84]: 
one      2.028126
three    2.705242
two      2.185666

In [85]: df.apply(np.cumsum)
Out[85]: 
        one     three       two
a  0.956147       NaN -1.489977
b  1.312776  0.053522 -0.974843
c  0.240797 -1.267815 -1.512050
d       NaN  0.116091 -0.816361

In [86]: df.apply(np.exp)
Out[86]: 
        one     three       two
a  2.601653       NaN  0.225378
b  1.428506  1.054980  1.673862
c  0.342330  0.266779  0.584378
d       NaN  3.990455  2.005091

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 [87]: tsdf = DataFrame(randn(1000, 3), columns=['A', 'B', 'C'],
   ....:                  index=date_range('1/1/2000', periods=1000))
   ....:

In [88]: tsdf.apply(lambda x: x.index[x.dropna().argmax()])
Out[88]: 
A    2001-09-20 00:00:00
B    2002-07-18 00:00:00
C    2000-09-14 00:00:00

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 [89]: tsdf
Out[89]: 
                   A         B         C
2000-01-01  0.112369 -0.420109  0.236761
2000-01-02 -2.085993  1.200230  0.270973
2000-01-03  0.137031 -2.592520 -0.527588
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  0.366870 -1.548709 -0.564637
2000-01-09  0.490365  1.406134  0.732978
2000-01-10  0.928472 -0.388655 -0.733859

In [90]: tsdf.apply(Series.interpolate)
Out[90]: 
                   A         B         C
2000-01-01  0.112369 -0.420109  0.236761
2000-01-02 -2.085993  1.200230  0.270973
2000-01-03  0.137031 -2.592520 -0.527588
2000-01-04  0.182999 -2.383758 -0.534998
2000-01-05  0.228967 -2.174996 -0.542407
2000-01-06  0.274934 -1.966234 -0.549817
2000-01-07  0.320902 -1.757471 -0.557227
2000-01-08  0.366870 -1.548709 -0.564637
2000-01-09  0.490365  1.406134  0.732978
2000-01-10  0.928472 -0.388655 -0.733859

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 [91]: f = lambda x: len(str(x))

In [92]: df['one'].map(f)
Out[92]: 
a    13
b    14
c    14
d     3
Name: one

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

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 [94]: s = Series(['six', 'seven', 'six', 'seven', 'six'],
   ....:            index=['a', 'b', 'c', 'd', 'e'])
   ....:

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

In [96]: s
Out[96]: 
a      six
b    seven
c      six
d    seven
e      six

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

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 [98]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])

In [99]: s
Out[99]: 
a   -0.984217
b   -0.298169
c    1.083151
d    1.174585
e    1.186910

In [100]: s.reindex(['e', 'b', 'f', 'd'])
Out[100]: 
e    1.186910
b   -0.298169
f         NaN
d    1.174585

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 [101]: df
Out[101]: 
        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689

In [102]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
Out[102]: 
      three       two       one
c -1.321336 -0.537207 -1.071979
f       NaN       NaN       NaN
b  0.053522  0.515133  0.356629

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 [103]: rs = s.reindex(df.index)

In [104]: rs
Out[104]: 
a   -0.984217
b   -0.298169
c    1.083151
d    1.174585

In [105]: rs.index is df.index
Out[105]: 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 [106]: df
Out[106]: 
        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689

In [107]: df2
Out[107]: 
        one       two
a  0.875881 -0.985960
b  0.276364  1.019150
c -1.152245 -0.033191

In [108]: df.reindex_like(df2)
Out[108]: 
        one       two
a  0.956147 -1.489977
b  0.356629  0.515133
c -1.071979 -0.537207

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 [109]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])

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

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

In [112]: s1.align(s2)
Out[112]: 
(a    1.425264
b    0.719895
c   -0.903348
d   -0.163582
e         NaN,
 a         NaN
b    0.719895
c   -0.903348
d   -0.163582
e   -1.225623)

In [113]: s1.align(s2, join='inner')
Out[113]: 
(b    0.719895
c   -0.903348
d   -0.163582,
 b    0.719895
c   -0.903348
d   -0.163582)

In [114]: s1.align(s2, join='left')
Out[114]: 
(a    1.425264
b    0.719895
c   -0.903348
d   -0.163582,
 a         NaN
b    0.719895
c   -0.903348
d   -0.163582)

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

In [115]: df.align(df2, join='inner')
Out[115]: 
(        one       two
a  0.956147 -1.489977
b  0.356629  0.515133
c -1.071979 -0.537207,
         one       two
a  0.875881 -0.985960
b  0.276364  1.019150
c -1.152245 -0.033191)

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

In [116]: df.align(df2, join='inner', axis=0)
Out[116]: 
(        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207,
         one       two
a  0.875881 -0.985960
b  0.276364  1.019150
c -1.152245 -0.033191)

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 [117]: df.align(df2.ix[0], axis=1)
Out[117]: 
(        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689,
 one      0.875881
three         NaN
two     -0.985960
Name: a)

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 [118]: rng = date_range('1/3/2000', periods=8)

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

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

In [121]: ts
Out[121]: 
2000-01-03    0.348299
2000-01-04    0.614990
2000-01-05    0.429119
2000-01-06    0.596947
2000-01-07    0.924013
2000-01-08   -0.889769
2000-01-09    1.772978
2000-01-10   -0.557704
Freq: D

In [122]: ts2
Out[122]: 
2000-01-03    0.348299
2000-01-06    0.596947
2000-01-09    1.772978

In [123]: ts2.reindex(ts.index)
Out[123]: 
2000-01-03    0.348299
2000-01-04         NaN
2000-01-05         NaN
2000-01-06    0.596947
2000-01-07         NaN
2000-01-08         NaN
2000-01-09    1.772978
2000-01-10         NaN
Freq: D

In [124]: ts2.reindex(ts.index, method='ffill')
Out[124]: 
2000-01-03    0.348299
2000-01-04    0.348299
2000-01-05    0.348299
2000-01-06    0.596947
2000-01-07    0.596947
2000-01-08    0.596947
2000-01-09    1.772978
2000-01-10    1.772978
Freq: D

In [125]: ts2.reindex(ts.index, method='bfill')
Out[125]: 
2000-01-03    0.348299
2000-01-04    0.596947
2000-01-05    0.596947
2000-01-06    0.596947
2000-01-07    1.772978
2000-01-08    1.772978
2000-01-09    1.772978
2000-01-10         NaN
Freq: D

Note the same result could have been achieved using fillna:

In [126]: ts2.reindex(ts.index).fillna(method='ffill')
Out[126]: 
2000-01-03    0.348299
2000-01-04    0.348299
2000-01-05    0.348299
2000-01-06    0.596947
2000-01-07    0.596947
2000-01-08    0.596947
2000-01-09    1.772978
2000-01-10    1.772978
Freq: D

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 [127]: df
Out[127]: 
        one     three       two
a  0.956147       NaN -1.489977
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207
d       NaN  1.383905  0.695689

In [128]: df.drop(['a', 'd'], axis=0)
Out[128]: 
        one     three       two
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207

In [129]: df.drop(['one'], axis=1)
Out[129]: 
      three       two
a       NaN -1.489977
b  0.053522  0.515133
c -1.321336 -0.537207
d  1.383905  0.695689

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

In [130]: df.reindex(df.index - ['a', 'd'])
Out[130]: 
        one     three       two
b  0.356629  0.053522  0.515133
c -1.071979 -1.321336 -0.537207

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 [131]: s
Out[131]: 
a    1.425264
b    0.719895
c   -0.903348
d   -0.163582
e   -1.225623

In [132]: s.rename(str.upper)
Out[132]: 
A    1.425264
B    0.719895
C   -0.903348
D   -0.163582
E   -1.225623

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 [133]: df.rename(columns={'one' : 'foo', 'two' : 'bar'},
   .....:           index={'a' : 'apple', 'b' : 'banana', 'd' : 'durian'})
   .....:
Out[133]: 
             foo     three       bar
apple   0.956147       NaN -1.489977
banana  0.356629  0.053522  0.515133
c      -1.071979 -1.321336 -0.537207
durian       NaN  1.383905  0.695689

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 [134]: 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 [135]: for item, frame in wp.iteritems():
   .....:     print item
   .....:     print frame
   .....:
Item1
                   A         B         C         D
2000-01-01  0.495524  0.834492  0.947785  0.853156
2000-01-02 -0.120785  0.503835 -1.033374  0.558859
2000-01-03 -2.146378 -2.222360 -0.439371 -0.196339
2000-01-04 -0.271494 -0.454723  0.676969 -0.577643
2000-01-05 -0.161275 -0.175661 -0.154328 -1.121515
Item2
                   A         B         C         D
2000-01-01  0.785140  0.099863  0.163869 -0.240119
2000-01-02  0.192305  0.987609 -0.207847  1.590817
2000-01-03 -1.269517 -0.844751  0.409726  0.573498
2000-01-04  0.795438  0.557014 -0.828152  0.181673
2000-01-05 -0.348820 -0.151335  1.390002  0.941237

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 [136]: for row_index, row in df2.iterrows():
   .....:     print '%s\n%s' % (row_index, row)
   .....:
a
one    0.875881
two   -0.985960
Name: a
b
one    0.276364
two    1.019150
Name: b
c
one   -1.152245
two   -0.033191
Name: c

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

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

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

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

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

In [141]: 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 [142]: for r in df2.itertuples(): print r
(0, 1, 4)
(1, 2, 5)
(2, 3, 6)

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 [143]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
   .....:                          columns=['three', 'two', 'one'])
   .....:

In [144]: unsorted_df.sort_index()
Out[144]: 
      three       two       one
a       NaN -1.489977  0.956147
b  0.053522  0.515133  0.356629
c -1.321336 -0.537207 -1.071979
d  1.383905  0.695689       NaN

In [145]: unsorted_df.sort_index(ascending=False)
Out[145]: 
      three       two       one
d  1.383905  0.695689       NaN
c -1.321336 -0.537207 -1.071979
b  0.053522  0.515133  0.356629
a       NaN -1.489977  0.956147

In [146]: unsorted_df.sort_index(axis=1)
Out[146]: 
        one     three       two
a  0.956147       NaN -1.489977
d       NaN  1.383905  0.695689
c -1.071979 -1.321336 -0.537207
b  0.356629  0.053522  0.515133

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 [147]: df.sort_index(by='two')
Out[147]: 
        one     three       two
a  0.956147       NaN -1.489977
c -1.071979 -1.321336 -0.537207
b  0.356629  0.053522  0.515133
d       NaN  1.383905  0.695689

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

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

In [149]: df[['one', 'two', 'three']].sort_index(by=['one','two'])
Out[149]: 
   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 [150]: s[2] = np.nan

In [151]: s.order()
Out[151]: 
e   -1.225623
d   -0.163582
b    0.719895
a    1.425264
c         NaN

In [152]: s.order(na_last=False)
Out[152]: 
c         NaN
e   -1.225623
d   -0.163582
b    0.719895
a    1.425264

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 [153]: df = DataFrame(np.arange(12).reshape((4, 3)))

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

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

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

In [157]: df[0].dtype
Out[157]: 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 [158]: df = DataFrame(randn(6, 3), columns=['a', 'b', 'c'])

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

In [160]: df
Out[160]: 
          a         b         c    d
0  0.272527  0.613177  1.593291  foo
1 -0.575896  0.751087 -0.411356  foo
2  1.151225  1.185217 -1.153065  foo
3 -2.676509  0.904457  2.691344  foo
4 -0.254256 -0.137338  0.188537  foo
5 -0.411671 -0.359300  2.387468  foo

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

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

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

In [164]: converted.dtypes
Out[164]: 
a    float64
b    float64
c    float64
d     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 [165]: df
Out[165]: 
           a          b          c    d
0  0.2725267   0.613177   1.593291  foo
1 -0.5758956  0.7510875 -0.4113564  foo
2   1.151225   1.185217  -1.153065  foo
3  -2.676509  0.9044572   2.691344  foo
4 -0.2542563 -0.1373385  0.1885367  foo
5 -0.4116706 -0.3593001   2.387468  foo

In [166]: 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 [167]: load('foo.pickle')
Out[167]: 
           a          b          c    d
0  0.2725267   0.613177   1.593291  foo
1 -0.5758956  0.7510875 -0.4113564  foo
2   1.151225   1.185217  -1.153065  foo
3  -2.676509  0.9044572   2.691344  foo
4 -0.2542563 -0.1373385  0.1885367  foo
5 -0.4116706 -0.3593001   2.387468  foo

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

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

In [169]: load('foo.pickle')
Out[169]: 
           a          b          c    d
0  0.2725267   0.613177   1.593291  foo
1 -0.5758956  0.7510875 -0.4113564  foo
2   1.151225   1.185217  -1.153065  foo
3  -2.676509  0.9044572   2.691344  foo
4 -0.2542563 -0.1373385  0.1885367  foo
5 -0.4116706 -0.3593001   2.387468  foo

Console Output Formatting

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 [170]: set_eng_float_format(accuracy=3, use_eng_prefix=True)

In [171]: df['a']/1.e3
Out[171]: 
0    272.527u
1   -575.896u
2      1.151m
3     -2.677m
4   -254.256u
5   -411.671u
Name: a

In [172]: df['a']/1.e6
Out[172]: 
0    272.527n
1   -575.896n
2      1.151u
3     -2.677u
4   -254.256n
5   -411.671n
Name: a

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.