### Navigation

- index
- modules |
- next |
- previous |
- pandas 0.13.1 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.199038
    1    1.095864
    2   -0.200875
    3    0.162291
    4   -0.430489
    dtype: float64

    In [7]: long_series.tail(3)
    Out[7]:
    997   -1.198693
    998    1.238029
    999   -1.344716
    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  0.232465 -0.789552 -0.364308
    2000-01-02 -0.534541  0.822239 -0.443109

    [2 rows x 3 columns]

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

    In [10]: df
    Out[10]:
                       a         b         c
    2000-01-01  0.232465 -0.789552 -0.364308
    2000-01-02 -0.534541  0.822239 -0.443109
    2000-01-03 -2.119990 -0.460149  1.813962
    2000-01-04 -1.053571  0.009412 -0.165966
    2000-01-05 -0.848662 -0.495553 -0.176421
    2000-01-06 -0.423595 -1.035433 -1.035374
    2000-01-07 -2.369079  0.524408 -0.871120
    2000-01-08  1.585433  0.039501  2.274101

    [8 rows x 3 columns]

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

    In [11]: s.values
    Out[11]: array([ 1.1292,  0.2313, -0.1847, -0.1386, -0.9243])

    In [12]: df.values
    Out[12]:
    array([[ 0.2325, -0.7896, -0.3643],
           [-0.5345,  0.8222, -0.4431],
           [-2.12  , -0.4601,  1.814 ],
           [-1.0536,  0.0094, -0.166 ],
           [-0.8487, -0.4956, -0.1764],
           [-0.4236, -1.0354, -1.0354],
           [-2.3691,  0.5244, -0.8711],
           [ 1.5854,  0.0395,  2.2741]])

    In [13]: wp.values
    Out[13]:
    array([[[-1.1181,  0.4313,  0.5547, -1.3336],
            [-0.3322, -0.4859,  1.7259,  1.7993],
            [-0.9689, -0.7795, -2.0007, -1.8666],
            [-1.1013,  1.9575,  0.0589,  0.7581],
            [ 0.0766, -0.5485, -0.1605, -0.3778]],

           [[ 0.2499, -0.3413, -0.2726, -0.2774],
            [-1.1029,  0.1003, -1.6028,  0.9201],
            [-0.6439,  0.0603, -0.4349, -0.4943],
            [ 0.738 ,  0.4516,  0.3341, -0.7871],
            [ 0.6514, -0.7419,  1.1939, -2.3958]]])

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.

## Accelerated operations

Pandas has support for accelerating certain types of binary numerical and boolean operations using the `numexpr` library (starting in 0.11.0) and the `bottleneck` libraries.

These libraries are especially useful when dealing with large data sets, and provide large speedups. `numexpr` uses smart chunking, caching, and multiple cores. `bottleneck` is a set of specialized cython routines that are especially fast when dealing with arrays that have `nans`.

Here is a sample (using 100 column x 100,000 row `DataFrames`):

Operation | 0.11.0 (ms) | Prior Version (ms) | Ratio to Prior
--- | --- | --- | ---
`df1 > df2` | 13.32 | 125.35 | 0.1063
`df1 * df2` | 21.71 | 36.63 | 0.5928
`df1 + df2` | 22.04 | 36.50 | 0.6039

You are highly encouraged to install both libraries. See the section Recommended Dependencies for more installation info.

## 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 = df_orig = DataFrame(d)

    In [16]: df
    Out[16]:
            one     three       two
    a -0.701368       NaN -0.087103
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666
    d       NaN -0.167407  0.104044

    [4 rows x 3 columns]

    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.810701       NaN -0.724777
    b  0.000000  0.000000  0.000000
    c -0.340950  0.205973 -0.640340
    d       NaN  0.186952 -0.533630

    [4 rows x 3 columns]

    In [20]: df.sub(row, axis=1)
    Out[20]:
            one     three       two
    a -0.810701       NaN -0.724777
    b  0.000000  0.000000  0.000000
    c -0.340950  0.205973 -0.640340
    d       NaN  0.186952 -0.533630

    [4 rows x 3 columns]

    In [21]: df.sub(column, axis='index')
    Out[21]:
            one     three  two
    a -0.614265       NaN    0
    b -0.528341 -0.992033    0
    c -0.228950 -0.145720    0
    d       NaN -0.271451    0

    [4 rows x 3 columns]

    In [22]: df.sub(column, axis=0)
    Out[22]:
            one     three  two
    a -0.614265       NaN    0
    b -0.528341 -0.992033    0
    c -0.228950 -0.145720    0
    d       NaN -0.271451    0

    [4 rows x 3 columns]

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.688773 -0.021497
    B  0.114982 -0.094183
    C  0.035674 -0.156470
    D -0.204142 -0.606887

    [4 rows x 2 columns]

    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.701368       NaN -0.087103
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666
    d       NaN -0.167407  0.104044

    [4 rows x 3 columns]

    In [27]: df2
    Out[27]:
            one     three       two
    a -0.701368  1.000000 -0.087103
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666
    d       NaN -0.167407  0.104044

    [4 rows x 3 columns]

    In [28]: df + df2
    Out[28]:
            one     three       two
    a -1.402736       NaN -0.174206
    b  0.218666 -0.708719  1.275347
    c -0.463233 -0.296773 -0.005333
    d       NaN -0.334814  0.208088

    [4 rows x 3 columns]

    In [29]: df.add(df2, fill_value=0)
    Out[29]:
            one     three       two
    a -1.402736  1.000000 -0.174206
    b  0.218666 -0.708719  1.275347
    c -0.463233 -0.296773 -0.005333
    d       NaN -0.334814  0.208088

    [4 rows x 3 columns]

### 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

    [4 rows x 3 columns]

    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

    [4 rows x 3 columns]

These operations produce a pandas object the same type as the left-hand-side input that if of dtype `bool`. These `boolean` objects can be used in indexing operations, see here

### Boolean Reductions

You can apply the reductions: `empty`, `any()`, `all()`, and `bool()` to provide a way to summarize a boolean result.

    In [32]: (df>0).all()
    Out[32]:
    one      False
    three    False
    two      False
    dtype: bool

    In [33]: (df>0).any()
    Out[33]:
    one       True
    three    False
    two       True
    dtype: bool

You can reduce to a final boolean value.

    In [34]: (df>0).any().any()
    Out[34]: True

You can test if a pandas object is empty, via the `empty` property.

    In [35]: df.empty
    Out[35]: False

    In [36]: DataFrame(columns=list('ABC')).empty
    Out[36]: True

To evaluate single-element pandas objects in a boolean context, use the method `.bool()`:

    In [37]: Series([True]).bool()
    Out[37]: True

    In [38]: Series([False]).bool()
    Out[38]: False

    In [39]: DataFrame([[True]]).bool()
    Out[39]: True

    In [40]: DataFrame([[False]]).bool()
    Out[40]: False

Warning

You might be tempted to do the following:

    >>>if df:
         ...

Or

    >>> df and df2

These both will raise as you are trying to compare multiple values.

    ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().

See gotchas for a more detailed discussion.

### Comparing if objects are equivalent

Often you may find there is more than one way to compute the same result. As a simple example, consider `df+df` and `df*2`. To test that these two computations produce the same result, given the tools shown above, you might imagine using `(df+df == df*2).all()`. But in fact, this expression is False:

    In [41]: df+df == df*2
    Out[41]:
         one  three   two
    a   True  False  True
    b   True   True  True
    c   True   True  True
    d  False   True  True

    [4 rows x 3 columns]

    In [42]: (df+df == df*2).all()
    Out[42]:
    one      False
    three    False
    two       True
    dtype: bool

Notice that the boolean DataFrame `df+df == df*2` contains some False values! That is because NaNs do not compare as equals:

    In [43]: np.nan == np.nan
    Out[43]: False

So, as of v0.13.1, NDFrames (such as Series, DataFrames, and Panels) have an `equals` method for testing equality, with NaNs in corresponding locations treated as equal.

    In [44]: (df+df).equals(df*2)
    Out[44]: True

### 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 [45]: df1 = DataFrame({'A' : [1., np.nan, 3., 5., np.nan],
       ....:                  'B' : [np.nan, 2., 3., np.nan, 6.]})
       ....:

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

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

    [5 rows x 2 columns]

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

    [6 rows x 2 columns]

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

    [6 rows x 2 columns]

### 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 [50]: combiner = lambda x, y: np.where(isnull(x), y, x)

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

    [6 rows x 2 columns]

## 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 [52]: df
    Out[52]:
            one     three       two
    a -0.701368       NaN -0.087103
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666
    d       NaN -0.167407  0.104044

    [4 rows x 3 columns]

    In [53]: df.mean(0)
    Out[53]:
    one     -0.274551
    three   -0.223384
    two      0.162987
    dtype: float64

    In [54]: df.mean(1)
    Out[54]:
    a   -0.394235
    b    0.130882
    c   -0.127557
    d   -0.031682
    dtype: float64

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

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

    In [56]: df.sum(axis=1, skipna=True)
    Out[56]:
    a   -0.788471
    b    0.392647
    c   -0.382670
    d   -0.063363
    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 [57]: ts_stand = (df - df.mean()) / df.std()

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

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

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

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

    In [61]: df.cumsum()
    Out[61]:
            one     three       two
    a -0.701368       NaN -0.087103
    b -0.592035 -0.354359  0.550570
    c -0.823652 -0.502746  0.547904
    d       NaN -0.670153  0.651948

    [4 rows x 3 columns]

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
`mode` | Mode
`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 [62]: np.mean(df['one'])
    Out[62]: -0.27455055654271204

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

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

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

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

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

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

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

    In [70]: series.describe()
    Out[70]:
    count    500.000000
    mean      -0.019898
    std        1.019180
    min       -2.628792
    25%       -0.649795
    50%       -0.059405
    75%        0.651932
    max        3.240991
    dtype: float64

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

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

    In [73]: frame.describe()
    Out[73]:
                    a           b           c           d           e
    count  500.000000  500.000000  500.000000  500.000000  500.000000
    mean     0.051388    0.053476   -0.035612    0.015388    0.057804
    std      0.989217    0.995961    0.977047    0.968385    1.022528
    min     -3.224136   -2.606460   -2.762875   -2.961757   -2.829100
    25%     -0.657420   -0.597123   -0.688961   -0.695019   -0.738097
    50%      0.042928    0.018837   -0.071830   -0.011326    0.073287
    75%      0.702445    0.693542    0.600454    0.680924    0.807670
    max      3.034008    3.104512    2.812028    2.623914    3.542846

    [8 rows x 5 columns]

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

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

    In [75]: s.describe()
    Out[75]:
    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 [76]: s1 = Series(randn(5))

    In [77]: s1
    Out[77]:
    0   -0.574018
    1    0.668292
    2    0.303418
    3   -1.190271
    4    0.138399
    dtype: float64

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

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

    In [80]: df1
    Out[80]:
              A         B         C
    0 -0.184355 -1.054354 -1.613138
    1 -0.050807 -2.130168 -1.852271
    2  0.455674  2.571061 -1.152538
    3 -1.638940 -0.364831 -0.348520
    4  0.202856  0.777088 -0.358316

    [5 rows x 3 columns]

    In [81]: df1.idxmin(axis=0)
    Out[81]:
    A    3
    B    1
    C    1
    dtype: int64

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

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

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

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

    [5 rows x 1 columns]

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

Note

`idxmin` and `idxmax` are called `argmin` and `argmax` in NumPy.

### Value counts (histogramming) / Mode

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

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

    In [88]: s = Series(data)

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

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

Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame:

    In [91]: s5 = Series([1, 1, 3, 3, 3, 5, 5, 7, 7, 7])

    In [92]: s5.mode()
    Out[92]:
    0    3
    1    7
    dtype: int64

    In [93]: df5 = DataFrame({"A": np.random.randint(0, 7, size=50),
       ....:                  "B": np.random.randint(-10, 15, size=50)})
       ....:

    In [94]: df5.mode()
    Out[94]:
       A   B
    0  5  -4
    1  6 NaN

    [2 rows x 2 columns]

### Discretization and quantiling

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

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

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

    In [97]: factor
    Out[97]:
     (-0.886, -0.0912]
     (-0.886, -0.0912]
     (-0.886, -0.0912]
        (1.493, 2.285]
        (0.701, 1.493]
    ...
      (-0.0912, 0.701]
     (-0.886, -0.0912]
        (0.701, 1.493]
        (0.701, 1.493]
      (-0.0912, 0.701]
        (1.493, 2.285]
    Levels (4): Index(['(-0.886, -0.0912]', '(-0.0912, 0.701]',
                       '(0.701, 1.493]', '(1.493, 2.285]'], dtype=object)
    Length: 20

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

    In [99]: factor
    Out[99]:
     (-1, 0]
     (-1, 0]
     (-1, 0]
      (1, 5]
      (1, 5]
    ...
      (0, 1]
     (-1, 0]
      (0, 1]
      (0, 1]
      (0, 1]
      (1, 5]
    Levels (4): Index(['(-5, -1]', '(-1, 0]', '(0, 1]', '(1, 5]'], dtype=object)
    Length: 20

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

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

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

    In [102]: factor
    Out[102]:
     [-1.861, -0.487]
      (0.0554, 0.658]
       (0.658, 2.259]
     [-1.861, -0.487]
       (0.658, 2.259]
    ...
      (0.0554, 0.658]
      (0.0554, 0.658]
       (0.658, 2.259]
     [-1.861, -0.487]
      (0.0554, 0.658]
     (-0.487, 0.0554]
    Levels (4): Index(['[-1.861, -0.487]', '(-0.487, 0.0554]',
                       '(0.0554, 0.658]', '(0.658, 2.259]'], dtype=object)
    Length: 30

    In [103]: value_counts(factor)
    Out[103]:
    (0.658, 2.259]      8
    [-1.861, -0.487]    8
    (0.0554, 0.658]     7
    (-0.487, 0.0554]    7
    dtype: int64

We can also pass infinite values to define the bins:

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

    In [105]: factor = cut(arr, [-np.inf, 0, np.inf])

    In [106]: factor
    Out[106]:
      (0, inf]
      (0, inf]
     (-inf, 0]
      (0, inf]
     (-inf, 0]
    ...
     (-inf, 0]
      (0, inf]
      (0, inf]
     (-inf, 0]
      (0, inf]
     (-inf, 0]
    Levels (2): Index(['(-inf, 0]', '(0, inf]'], dtype=object)
    Length: 20

## 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 [107]: df.apply(np.mean)
    Out[107]:
    one     -0.274551
    three   -0.223384
    two      0.162987
    dtype: float64

    In [108]: df.apply(np.mean, axis=1)
    Out[108]:
    a   -0.394235
    b    0.130882
    c   -0.127557
    d   -0.031682
    dtype: float64

    In [109]: df.apply(lambda x: x.max() - x.min())
    Out[109]:
    one      0.810701
    three    0.205973
    two      0.724777
    dtype: float64

    In [110]: df.apply(np.cumsum)
    Out[110]:
            one     three       two
    a -0.701368       NaN -0.087103
    b -0.592035 -0.354359  0.550570
    c -0.823652 -0.502746  0.547904
    d       NaN -0.670153  0.651948

    [4 rows x 3 columns]

    In [111]: df.apply(np.exp)
    Out[111]:
            one     three       two
    a  0.495907       NaN  0.916583
    b  1.115534  0.701623  1.892074
    c  0.793250  0.862098  0.997337
    d       NaN  0.845855  1.109649

    [4 rows x 3 columns]

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

    In [113]: tsdf.apply(lambda x: x.idxmax())
    Out[113]:
    A   2002-08-19
    B   2000-11-30
    C   2002-01-10
    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 [114]: tsdf
    Out[114]:
                       A         B         C
    2000-01-01 -1.226159  0.173875 -0.798063
    2000-01-02  0.127076  0.141070 -2.186743
    2000-01-03 -1.804229  0.879800  0.465165
    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.542261  0.524780  1.445690
    2000-01-09 -1.104998 -0.470200  0.336180
    2000-01-10 -0.947692 -0.262122 -0.423769

    [10 rows x 3 columns]

    In [115]: tsdf.apply(Series.interpolate)
    Out[115]:
                       A         B         C
    2000-01-01 -1.226159  0.173875 -0.798063
    2000-01-02  0.127076  0.141070 -2.186743
    2000-01-03 -1.804229  0.879800  0.465165
    2000-01-04 -1.134931  0.808796  0.661270
    2000-01-05 -0.465633  0.737792  0.857375
    2000-01-06  0.203665  0.666788  1.053480
    2000-01-07  0.872963  0.595784  1.249585
    2000-01-08  1.542261  0.524780  1.445690
    2000-01-09 -1.104998 -0.470200  0.336180
    2000-01-10 -0.947692 -0.262122 -0.423769

    [10 rows x 3 columns]

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 [116]: df4
    Out[116]:
            one     three       two
    a -0.701368       NaN -0.087103
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666
    d       NaN -0.167407  0.104044

    [4 rows x 3 columns]

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

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

    In [119]: df4.applymap(f)
    Out[119]:
       one  three  two
    a   15      3   16
    b   14     15   14
    c   15     15   17
    d    3     15   14

    [4 rows x 3 columns]

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

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

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

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

### Applying with a Panel

Applying with a `Panel` will pass a `Series` to the applied function. If the applied function returns a `Series`, the result of the application will be a `Panel`. If the applied function reduces to a scalar, the result of the application will be a `DataFrame`.

Note

Prior to 0.13.1 `apply` on a `Panel` would only work on `ufuncs` (e.g. `np.sum/np.max`).

    In [124]: import pandas.util.testing as tm

    In [125]: panel = tm.makePanel(5)

    In [126]: panel
    Out[126]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
    Items axis: ItemA to ItemC
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: A to D

    In [127]: panel['ItemA']
    Out[127]:
                       A         B         C         D
    2000-01-03  0.166882 -0.597361 -1.200639  0.174260
    2000-01-04 -1.759496 -1.514940 -1.872993 -0.581163
    2000-01-05  0.901336 -1.640398  0.825210  0.087916
    2000-01-06 -0.317478 -1.130643 -0.392715  0.416971
    2000-01-07 -0.681335 -0.245890 -1.994150  0.666084

    [5 rows x 4 columns]

A transformational apply.

    In [128]: result = panel.apply(lambda x: x*2, axis='items')

    In [129]: result
    Out[129]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
    Items axis: ItemA to ItemC
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: A to D

    In [130]: result['ItemA']
    Out[130]:
                       A         B         C         D
    2000-01-03  0.333764 -1.194722 -2.401278  0.348520
    2000-01-04 -3.518991 -3.029880 -3.745986 -1.162326
    2000-01-05  1.802673 -3.280796  1.650421  0.175832
    2000-01-06 -0.634955 -2.261286 -0.785430  0.833943
    2000-01-07 -1.362670 -0.491779 -3.988300  1.332168

    [5 rows x 4 columns]

A reduction operation.

    In [131]: panel.apply(lambda x: x.dtype, axis='items')
    Out[131]:
                      A        B        C        D
    2000-01-03  float64  float64  float64  float64
    2000-01-04  float64  float64  float64  float64
    2000-01-05  float64  float64  float64  float64
    2000-01-06  float64  float64  float64  float64
    2000-01-07  float64  float64  float64  float64

    [5 rows x 4 columns]

A similar reduction type operation

    In [132]: panel.apply(lambda x: x.sum(), axis='major_axis')
    Out[132]:
          ItemA     ItemB     ItemC
    A -1.690090  1.840259  0.010754
    B -5.129232  0.860182  0.178018
    C -4.635286  0.545328  2.456520
    D  0.764068 -3.623586  1.761541

    [4 rows x 3 columns]

This last reduction is equivalent to

    In [133]: panel.sum('major_axis')
    Out[133]:
          ItemA     ItemB     ItemC
    A -1.690090  1.840259  0.010754
    B -5.129232  0.860182  0.178018
    C -4.635286  0.545328  2.456520
    D  0.764068 -3.623586  1.761541

    [4 rows x 3 columns]

A transformation operation that returns a `Panel`, but is computing the z-score across the `major_axis`.

    In [134]: result = panel.apply(
       .....:            lambda x: (x-x.mean())/x.std(),
       .....:            axis='major_axis')
       .....:

    In [135]: result
    Out[135]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
    Items axis: ItemA to ItemC
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: A to D

    In [136]: result['ItemA']
    Out[136]:
                       A         B         C         D
    2000-01-03  0.509389  0.719204 -0.234072  0.045812
    2000-01-04 -1.434116 -0.820934 -0.809328 -1.567858
    2000-01-05  1.250373 -1.031513  1.499214 -0.138629
    2000-01-06  0.020723 -0.175899  0.457175  0.564271
    2000-01-07 -0.346370  1.309142 -0.912988  1.096405

    [5 rows x 4 columns]

Apply can also accept multiple axes in the `axis` argument. This will pass a `DataFrame` of the cross-section to the applied function.

    In [137]: f = lambda x: ((x.T-x.mean(1))/x.std(1)).T

    In [138]: result = panel.apply(f, axis = ['items','major_axis'])

    In [139]: result
    Out[139]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
    Items axis: A to D
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: ItemA to ItemC

    In [140]: result.loc[:,:,'ItemA']
    Out[140]:
                       A         B         C         D
    2000-01-03  0.783778 -0.648605 -0.903128  0.450190
    2000-01-04 -0.884670 -1.046087 -1.096521 -0.900467
    2000-01-05  1.140729 -1.124651  0.716895  0.754324
    2000-01-06 -1.043494  0.029043 -0.991042  0.845339
    2000-01-07 -1.125870 -0.536928 -1.152240 -0.182526

    [5 rows x 4 columns]

This is equivalent to the following

    In [141]: result = Panel(dict([ (ax,f(panel.loc[:,:,ax]))
       .....:                         for ax in panel.minor_axis ]))
       .....:

    In [142]: result
    Out[142]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
    Items axis: A to D
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: ItemA to ItemC

    In [143]: result.loc[:,:,'ItemA']
    Out[143]:
                       A         B         C         D
    2000-01-03  0.783778 -0.648605 -0.903128  0.450190
    2000-01-04 -0.884670 -1.046087 -1.096521 -0.900467
    2000-01-05  1.140729 -1.124651  0.716895  0.754324
    2000-01-06 -1.043494  0.029043 -0.991042  0.845339
    2000-01-07 -1.125870 -0.536928 -1.152240 -0.182526

    [5 rows x 4 columns]

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

    In [145]: s
    Out[145]:
    a    1.112686
    b   -1.069046
    c   -1.218080
    d   -0.944778
    e    0.005240
    dtype: float64

    In [146]: s.reindex(['e', 'b', 'f', 'd'])
    Out[146]:
    e    0.005240
    b   -1.069046
    f         NaN
    d   -0.944778
    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 [147]: df
    Out[147]:
            one     three       two
    a -0.701368       NaN -0.087103
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666
    d       NaN -0.167407  0.104044

    [4 rows x 3 columns]

    In [148]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
    Out[148]:
          three       two       one
    c -0.148387 -0.002666 -0.231617
    f       NaN       NaN       NaN
    b -0.354359  0.637674  0.109333

    [3 rows x 3 columns]

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

    In [150]: rs
    Out[150]:
    a    1.112686
    b   -1.069046
    c   -1.218080
    d   -0.944778
    dtype: float64

    In [151]: rs.index is df.index
    Out[151]: 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 sprinkling 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 [152]: df2
    Out[152]:
            one       two
    a -0.701368 -0.087103
    b  0.109333  0.637674
    c -0.231617 -0.002666

    [3 rows x 2 columns]

    In [153]: df3
    Out[153]:
            one       two
    a -0.426817 -0.269738
    b  0.383883  0.455039
    c  0.042934 -0.185301

    [3 rows x 2 columns]

    In [154]: df.reindex_like(df2)
    Out[154]:
            one       two
    a -0.701368 -0.087103
    b  0.109333  0.637674
    c -0.231617 -0.002666

    [3 rows x 2 columns]

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

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

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

    In [158]: s1.align(s2)
    Out[158]:
    (a    0.479090
     b    0.686579
     c   -0.949750
     d   -0.257472
     e         NaN
     dtype: float64, a         NaN
     b    0.686579
     c   -0.949750
     d   -0.257472
     e   -0.568459
     dtype: float64)

    In [159]: s1.align(s2, join='inner')
    Out[159]:
    (b    0.686579
     c   -0.949750
     d   -0.257472
     dtype: float64, b    0.686579
     c   -0.949750
     d   -0.257472
     dtype: float64)

    In [160]: s1.align(s2, join='left')
    Out[160]:
    (a    0.479090
     b    0.686579
     c   -0.949750
     d   -0.257472
     dtype: float64, a         NaN
     b    0.686579
     c   -0.949750
     d   -0.257472
     dtype: float64)

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

    In [161]: df.align(df2, join='inner')
    Out[161]:
    (        one       two
     a -0.701368 -0.087103
     b  0.109333  0.637674
     c -0.231617 -0.002666

     [3 rows x 2 columns],         one       two
     a -0.701368 -0.087103
     b  0.109333  0.637674
     c -0.231617 -0.002666

     [3 rows x 2 columns])

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

    In [162]: df.align(df2, join='inner', axis=0)
    Out[162]:
    (        one     three       two
     a -0.701368       NaN -0.087103
     b  0.109333 -0.354359  0.637674
     c -0.231617 -0.148387 -0.002666

     [3 rows x 3 columns],         one       two
     a -0.701368 -0.087103
     b  0.109333  0.637674
     c -0.231617 -0.002666

     [3 rows x 2 columns])

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 [163]: df.align(df2.ix[0], axis=1)
    Out[163]:
    (        one     three       two
     a -0.701368       NaN -0.087103
     b  0.109333 -0.354359  0.637674
     c -0.231617 -0.148387 -0.002666
     d       NaN -0.167407  0.104044

     [4 rows x 3 columns], one     -0.701368
     three         NaN
     two     -0.087103
     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 [164]: rng = date_range('1/3/2000', periods=8)

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

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

    In [167]: ts
    Out[167]:
    2000-01-03   -0.059786
    2000-01-04    0.936271
    2000-01-05    0.040623
    2000-01-06    0.836517
    2000-01-07    1.849649
    2000-01-08   -1.198994
    2000-01-09    0.688500
    2000-01-10   -0.696903
    Freq: D, dtype: float64

    In [168]: ts2
    Out[168]:
    2000-01-03   -0.059786
    2000-01-06    0.836517
    2000-01-09    0.688500
    dtype: float64

    In [169]: ts2.reindex(ts.index)
    Out[169]:
    2000-01-03   -0.059786
    2000-01-04         NaN
    2000-01-05         NaN
    2000-01-06    0.836517
    2000-01-07         NaN
    2000-01-08         NaN
    2000-01-09    0.688500
    2000-01-10         NaN
    Freq: D, dtype: float64

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

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

Note these methods require that the indexes are order increasing.

Note the same result could have been achieved using fillna:

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

Note that `reindex` will raise a ValueError if the index is not monotonic. `fillna` will not make any checks on the order of the index.

### 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 [173]: df
    Out[173]:
            one     three       two
    a -0.701368       NaN -0.087103
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666
    d       NaN -0.167407  0.104044

    [4 rows x 3 columns]

    In [174]: df.drop(['a', 'd'], axis=0)
    Out[174]:
            one     three       two
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666

    [2 rows x 3 columns]

    In [175]: df.drop(['one'], axis=1)
    Out[175]:
          three       two
    a       NaN -0.087103
    b -0.354359  0.637674
    c -0.148387 -0.002666
    d -0.167407  0.104044

    [4 rows x 2 columns]

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

    In [176]: df.reindex(df.index - ['a', 'd'])
    Out[176]:
            one     three       two
    b  0.109333 -0.354359  0.637674
    c -0.231617 -0.148387 -0.002666

    [2 rows x 3 columns]

### 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 [177]: s
    Out[177]:
    a    0.479090
    b    0.686579
    c   -0.949750
    d   -0.257472
    e   -0.568459
    dtype: float64

    In [178]: s.rename(str.upper)
    Out[178]:
    A    0.479090
    B    0.686579
    C   -0.949750
    D   -0.257472
    E   -0.568459
    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 [179]: df.rename(columns={'one' : 'foo', 'two' : 'bar'},
       .....:           index={'a' : 'apple', 'b' : 'banana', 'd' : 'durian'})
       .....:
    Out[179]:
                 foo     three       bar
    apple  -0.701368       NaN -0.087103
    banana  0.109333 -0.354359  0.637674
    c      -0.231617 -0.148387 -0.002666
    durian       NaN -0.167407  0.104044

    [4 rows x 3 columns]

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 [180]: 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 [181]: for item, frame in wp.iteritems():
       .....:     print(item)
       .....:     print(frame)
       .....:
    Item1
                       A         B         C         D
    2000-01-01 -1.118121  0.431279  0.554724 -1.333649
    2000-01-02 -0.332174 -0.485882  1.725945  1.799276
    2000-01-03 -0.968916 -0.779465 -2.000701 -1.866630
    2000-01-04 -1.101268  1.957478  0.058889  0.758071
    2000-01-05  0.076612 -0.548502 -0.160485 -0.377780

    [5 rows x 4 columns]
    Item2
                       A         B         C         D
    2000-01-01  0.249911 -0.341270 -0.272599 -0.277446
    2000-01-02 -1.102896  0.100307 -1.602814  0.920139
    2000-01-03 -0.643870  0.060336 -0.434942 -0.494305
    2000-01-04  0.737973  0.451632  0.334124 -0.787062
    2000-01-05  0.651396 -0.741919  1.193881 -2.395763

    [5 rows x 4 columns]

### 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 [182]: for row_index, row in df2.iterrows():
       .....:     print('%s\n%s' % (row_index, row))
       .....:
    a
    one   -0.701368
    two   -0.087103
    Name: a, dtype: float64
    b
    one    0.109333
    two    0.637674
    Name: b, dtype: float64
    c
    one   -0.231617
    two   -0.002666
    Name: c, dtype: float64

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

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

    In [184]: print(df2)
       x  y
    0  1  4
    1  2  5
    2  3  6

    [3 rows x 2 columns]

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

    [2 rows x 3 columns]

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

    In [187]: print(df2_t)
       0  1  2
    x  1  2  3
    y  4  5  6

    [2 rows x 3 columns]

Note

`iterrows` does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames). For example,

>     In [188]: df_iter = DataFrame([[1, 1.0]], columns=['x', 'y'])

>     In [189]: row = next(df_iter.iterrows())[1]

>     In [190]: print(row['x'].dtype)
>     float64

>     In [191]: print(df_iter['x'].dtype)
>     int64

### 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 [192]: 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:

### Splitting and Replacing Strings

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

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

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

    In [196]: s.str.len()
    Out[196]:
    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 [197]: s2 = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])

    In [198]: s2.str.split('_')
    Out[198]:
    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 [199]: s2.str.split('_').str.get(1)
    Out[199]:
    0      b
    1      d
    2    NaN
    3      g
    dtype: object

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

Methods like `replace` and `findall` take regular expressions, too:

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

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

    In [203]: s3.str.replace('^.a|dog', 'XX-XX ', case=False)
    Out[203]:
    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

### Extracting Substrings

The method `extract` (introduced in version 0.13) accepts regular expressions with match groups. Extracting a regular expression with one group returns a Series of strings.

    In [204]: Series(['a1', 'b2', 'c3']).str.extract('[ab](\d)')
    Out[204]:
    0      1
    1      2
    2    NaN
    dtype: object

Elements that do not match return `NaN`. Extracting a regular expression with more than one group returns a DataFrame with one column per group.

    In [205]: Series(['a1', 'b2', 'c3']).str.extract('([ab])(\d)')
    Out[205]:
         0    1
    0    a    1
    1    b    2
    2  NaN  NaN

    [3 rows x 2 columns]

Elements that do not match return a row filled with `NaN`. Thus, a Series of messy strings can be “converted” into a like-indexed Series or DataFrame of cleaned-up or more useful strings, without necessitating `get()` to access tuples or `re.match` objects.

Named groups like

    In [206]: Series(['a1', 'b2', 'c3']).str.extract('(?P<letter>[ab])(?P<digit>\d)')
    Out[206]:
      letter digit
    0      a     1
    1      b     2
    2    NaN   NaN

    [3 rows x 2 columns]

and optional groups like

    In [207]: Series(['a1', 'b2', '3']).str.extract('(?P<letter>[ab])?(?P<digit>\d)')
    Out[207]:
      letter digit
    0      a     1
    1      b     2
    2    NaN     3

    [3 rows x 2 columns]

can also be used.

### Testing for Strings that Match or Contain a Pattern

You can check whether elements contain a pattern:

    In [208]: pattern = r'[a-z][0-9]'

    In [209]: Series(['1', '2', '3a', '3b', '03c']).str.contains(pattern)
    Out[209]:
    0    False
    1    False
    2    False
    3    False
    4    False
    dtype: bool

or match a pattern:

    In [210]: Series(['1', '2', '3a', '3b', '03c']).str.match(pattern, as_indexer=True)
    Out[210]:
    0    False
    1    False
    2    False
    3    False
    4    False
    dtype: bool

The distinction between `match` and `contains` is strictness: `match` relies on strict `re.match`, while `contains` relies on `re.search`.

Warning

In previous versions, `match` was for extracting groups, returning a not-so-convenient Series of tuples. The new method `extract` (described in the previous section) is now preferred.

This old, deprecated behavior of `match` is still the default. As demonstrated above, use the new behavior by setting `as_indexer=True`. In this mode, `match` is analogous to `contains`, returning a boolean Series. The new behavior will become the default behavior in a future release.

Methods like `match`, `contains`, `startswith`, and `endswith` take
  an extra `na` argument so missing values can be considered True or False:

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

    In [212]: s4.str.contains('A', na=False)
    Out[212]:
    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
`endswith` | 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
`extract` | Call `re.match` on each element, as `match` does, but return matched groups as strings for convenience.
`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`

### Getting indicator variables from seperated strings

You can extract dummy variables from string columns. For example if they are seperated by a `'|'`:

>     In [213]: s = pd.Series(['a', 'a|b', np.nan, 'a|c'])

>     In [214]: s.str.get_dummies(sep='|')
>     Out[214]:
>        a  b  c
>     0  1  0  0
>     1  1  1  0
>     2  0  0  0
>     3  1  0  1

>     [4 rows x 3 columns]

See also `get_dummies()`.

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

    In [216]: unsorted_df.sort_index()
    Out[216]:
          three       two       one
    a       NaN -0.087103 -0.701368
    b -0.354359  0.637674  0.109333
    c -0.148387 -0.002666 -0.231617
    d -0.167407  0.104044       NaN

    [4 rows x 3 columns]

    In [217]: unsorted_df.sort_index(ascending=False)
    Out[217]:
          three       two       one
    d -0.167407  0.104044       NaN
    c -0.148387 -0.002666 -0.231617
    b -0.354359  0.637674  0.109333
    a       NaN -0.087103 -0.701368

    [4 rows x 3 columns]

    In [218]: unsorted_df.sort_index(axis=1)
    Out[218]:
            one     three       two
    a -0.701368       NaN -0.087103
    d       NaN -0.167407  0.104044
    c -0.231617 -0.148387 -0.002666
    b  0.109333 -0.354359  0.637674

    [4 rows x 3 columns]

`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 [219]: df1 = DataFrame({'one':[2,1,1,1],'two':[1,3,2,4],'three':[5,4,3,2]})

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

    [4 rows x 3 columns]

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

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

    [4 rows x 3 columns]

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 [222]: s[2] = np.nan

    In [223]: s.order()
    Out[223]:
    0      a
    1    a|b
    3    a|c
    2    NaN
    dtype: object

    In [224]: s.order(na_last=False)
    Out[224]:
    2    NaN
    0      a
    1    a|b
    3    a|c
    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

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.

## dtypes

The main types stored in pandas objects are `float`, `int`, `bool`, `datetime64[ns]`, `timedelta[ns]`, and `object`. In addition these dtypes have item sizes, e.g. `int64` and `int32`. A convenient `dtypes` attribute for DataFrames returns a Series with the data type of each column.

    In [225]: dft = DataFrame(dict( A = np.random.rand(3),
       .....:                       B = 1,
       .....:                       C = 'foo',
       .....:                       D = Timestamp('20010102'),
       .....:                       E = Series([1.0]*3).astype('float32'),
       .....:                       F = False,
       .....:                       G = Series([1]*3,dtype='int8')))
       .....:

    In [226]: dft
    Out[226]:
              A  B    C          D  E      F  G
    0  0.298496  1  foo 2001-01-02  1  False  1
    1  0.347135  1  foo 2001-01-02  1  False  1
    2  0.141330  1  foo 2001-01-02  1  False  1

    [3 rows x 7 columns]

    In [227]: dft.dtypes
    Out[227]:
    A           float64
    B             int64
    C            object
    D    datetime64[ns]
    E           float32
    F              bool
    G              int8
    dtype: object

On a `Series` use the `dtype` method.

    In [228]: dft['A'].dtype
    Out[228]: dtype('float64')

If a pandas object contains data multiple dtypes IN A SINGLE COLUMN, the dtype of the column will be chosen to accommodate all of the data types (`object` is the most general).

    # these ints are coerced to floats
    In [229]: Series([1, 2, 3, 4, 5, 6.])
    Out[229]:
    0    1
    1    2
    2    3
    3    4
    4    5
    5    6
    dtype: float64

    # string data forces an ``object`` dtype
    In [230]: Series([1, 2, 3, 6., 'foo'])
    Out[230]:
    0      1
    1      2
    2      3
    3      6
    4    foo
    dtype: object

The method `get_dtype_counts` will return the number of columns of each type in a `DataFrame`:

    In [231]: dft.get_dtype_counts()
    Out[231]:
    bool              1
    datetime64[ns]    1
    float32           1
    float64           1
    int64             1
    int8              1
    object            1
    dtype: int64

Numeric dtypes will propagate and can coexist in DataFrames (starting in v0.11.0). If a dtype is passed (either directly via the `dtype` keyword, a passed `ndarray`, or a passed `Series`, then it will be preserved in DataFrame operations. Furthermore, different numeric dtypes will NOT be combined. The following example will give you a taste.

    In [232]: df1 = DataFrame(randn(8, 1), columns = ['A'], dtype = 'float32')

    In [233]: df1
    Out[233]:
              A
    0  1.111528
    1 -1.189947
    2 -0.652389
    3 -0.216515
    4 -2.163590
    5  0.117168
    6 -1.806383
    7 -0.249113

    [8 rows x 1 columns]

    In [234]: df1.dtypes
    Out[234]:
    A    float32
    dtype: object

    In [235]: df2 = DataFrame(dict( A = Series(randn(8),dtype='float16'),
       .....:                       B = Series(randn(8)),
       .....:                       C = Series(np.array(randn(8),dtype='uint8')) ))
       .....:

    In [236]: df2
    Out[236]:
              A         B    C
    0  1.109375 -0.265597    0
    1  0.748535 -1.841820    0
    2 -1.319336 -0.661921    0
    3  2.005859  1.198778    0
    4  0.260498  0.138315  254
    5  1.785156  0.967672    0
    6  0.481689  0.447494    2
    7  0.319336 -0.361367    2

    [8 rows x 3 columns]

    In [237]: df2.dtypes
    Out[237]:
    A    float16
    B    float64
    C      uint8
    dtype: object

### defaults

By default integer types are `int64` and float types are `float64`, REGARDLESS of platform (32-bit or 64-bit). The following will all result in `int64` dtypes.

    In [238]: DataFrame([1, 2], columns=['a']).dtypes
    Out[238]:
    a    int64
    dtype: object

    In [239]: DataFrame({'a': [1, 2]}).dtypes
    Out[239]:
    a    int64
    dtype: object

    In [240]: DataFrame({'a': 1 }, index=list(range(2))).dtypes
    Out[240]:
    a    int64
    dtype: object

Numpy, however will choose platform-dependent types when creating arrays. The following WILL result in `int32` on 32-bit platform.

    In [241]: frame = DataFrame(np.array([1, 2]))

### upcasting

Types can potentially be upcasted when combined with other types, meaning they are promoted from the current type (say `int` to `float`)

    In [242]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2

    In [243]: df3
    Out[243]:
              A         B    C
    0  2.220903 -0.265597    0
    1 -0.441412 -1.841820    0
    2 -1.971725 -0.661921    0
    3  1.789344  1.198778    0
    4 -1.903092  0.138315  254
    5  1.902324  0.967672    0
    6 -1.324694  0.447494    2
    7  0.070223 -0.361367    2

    [8 rows x 3 columns]

    In [244]: df3.dtypes
    Out[244]:
    A    float32
    B    float64
    C    float64
    dtype: object

The `values` attribute on a DataFrame return the lower-common-denominator of the dtypes, meaning the dtype that can accommodate ALL of the types in the resulting homogenous dtyped numpy array. This can force some upcasting.

    In [245]: df3.values.dtype
    Out[245]: dtype('float64')

### astype

You can use the `astype` method to explicitly convert dtypes from one to another. These will by default return a copy, even if the dtype was unchanged (pass `copy=False` to change this behavior). In addition, they will raise an exception if the astype operation is invalid.

Upcasting is always according to the numpy rules. If two different dtypes are involved in an operation, then the more general one will be used as the result of the operation.

    In [246]: df3
    Out[246]:
              A         B    C
    0  2.220903 -0.265597    0
    1 -0.441412 -1.841820    0
    2 -1.971725 -0.661921    0
    3  1.789344  1.198778    0
    4 -1.903092  0.138315  254
    5  1.902324  0.967672    0
    6 -1.324694  0.447494    2
    7  0.070223 -0.361367    2

    [8 rows x 3 columns]

    In [247]: df3.dtypes
    Out[247]:
    A    float32
    B    float64
    C    float64
    dtype: object

    # conversion of dtypes
    In [248]: df3.astype('float32').dtypes
    Out[248]:
    A    float32
    B    float32
    C    float32
    dtype: object

### object conversion

`convert_objects` is a method to try to force conversion of types from the `object` dtype to other types. To force conversion of specific types that are number like, e.g. could be a string that represents a number, pass `convert_numeric=True`. This will force strings and numbers alike to be numbers if possible, otherwise they will be set to `np.nan`.

    In [249]: df3['D'] = '1.'

    In [250]: df3['E'] = '1'

    In [251]: df3.convert_objects(convert_numeric=True).dtypes
    Out[251]:
    A    float32
    B    float64
    C    float64
    D    float64
    E      int64
    dtype: object

    # same, but specific dtype conversion
    In [252]: df3['D'] = df3['D'].astype('float16')

    In [253]: df3['E'] = df3['E'].astype('int32')

    In [254]: df3.dtypes
    Out[254]:
    A    float32
    B    float64
    C    float64
    D    float16
    E      int32
    dtype: object

To force conversion to `datetime64[ns]`, pass `convert_dates='coerce'`. This will convert any datetime-like object to dates, forcing other values to `NaT`. This might be useful if you are reading in data which is mostly dates, but occasionally has non-dates intermixed and you want to represent as missing.

    In [255]: s = Series([datetime(2001,1,1,0,0),
       .....:            'foo', 1.0, 1, Timestamp('20010104'),
       .....:            '20010105'],dtype='O')
       .....:

    In [256]: s
    Out[256]:
    0    2001-01-01 00:00:00
    1                    foo
    2                      1
    3                      1
    4    2001-01-04 00:00:00
    5               20010105
    dtype: object

    In [257]: s.convert_objects(convert_dates='coerce')
    Out[257]:
    0   2001-01-01
    1          NaT
    2          NaT
    3          NaT
    4   2001-01-04
    5   2001-01-05
    dtype: datetime64[ns]

In addition, `convert_objects` will attempt the soft conversion of any object dtypes, meaning that if all the objects in a Series are of the same type, the Series will have that dtype.

### gotchas

Performing selection operations on `integer` type data can easily upcast the data to `floating`. The dtype of the input data will be preserved in cases where `nans` are not introduced (starting in 0.11.0) See also integer na gotchas

    In [258]: dfi = df3.astype('int32')

    In [259]: dfi['E'] = 1

    In [260]: dfi
    Out[260]:
       A  B    C  D  E
    0  2  0    0  1  1
    1  0 -1    0  1  1
    2 -1  0    0  1  1
    3  1  1    0  1  1
    4 -1  0  254  1  1
    5  1  0    0  1  1
    6 -1  0    2  1  1
    7  0  0    2  1  1

    [8 rows x 5 columns]

    In [261]: dfi.dtypes
    Out[261]:
    A    int32
    B    int32
    C    int32
    D    int32
    E    int64
    dtype: object

    In [262]: casted = dfi[dfi>0]

    In [263]: casted
    Out[263]:
        A   B    C  D  E
    0   2 NaN  NaN  1  1
    1 NaN NaN  NaN  1  1
    2 NaN NaN  NaN  1  1
    3   1   1  NaN  1  1
    4 NaN NaN  254  1  1
    5   1 NaN  NaN  1  1
    6 NaN NaN    2  1  1
    7 NaN NaN    2  1  1

    [8 rows x 5 columns]

    In [264]: casted.dtypes
    Out[264]:
    A    float64
    B    float64
    C    float64
    D      int32
    E      int64
    dtype: object

While float dtypes are unchanged.

    In [265]: dfa = df3.copy()

    In [266]: dfa['A'] = dfa['A'].astype('float32')

    In [267]: dfa.dtypes
    Out[267]:
    A    float32
    B    float64
    C    float64
    D    float16
    E      int32
    dtype: object

    In [268]: casted = dfa[df2>0]

    In [269]: casted
    Out[269]:
              A         B    C   D   E
    0  2.220903       NaN  NaN NaN NaN
    1 -0.441412       NaN  NaN NaN NaN
    2       NaN       NaN  NaN NaN NaN
    3  1.789344  1.198778  NaN NaN NaN
    4 -1.903092  0.138315  254 NaN NaN
    5  1.902324  0.967672  NaN NaN NaN
    6 -1.324694  0.447494    2 NaN NaN
    7  0.070223       NaN    2 NaN NaN

    [8 rows x 5 columns]

    In [270]: casted.dtypes
    Out[270]:
    A    float32
    B    float64
    C    float64
    D    float16
    E    float64
    dtype: object

## Working with package options

New in version 0.10.1.

Pandas has an options system that let’s you customize some aspects of it’s behaviour, display-related options being those the user is must likely to adjust.

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 [271]: import pandas as pd

    In [272]: pd.options.display.max_rows
    Out[272]: 15

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

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

There is also an API composed of 4 relevant 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.

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

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

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

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

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

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

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

    In [280]: try:
       .....:     get_option("display.max_")
       .....: except KeyError as e:
       .....:     print(e)
       .....:
    'Pattern matched multiple keys'

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

You can get a list of available options and their descriptions with `describe_option`. When called with no argument `describe_option` will print out the descriptions for all available options.

    In [281]: 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, `max_columns` is still respected, but the output will
            wrap-around across multiple "pages" if it's width exceeds `display.width`.
    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.height: [default: 60] [currently: 60]
    : int
            Deprecated.
    	(Deprecated, use `display.max_rows` instead.)

    display.large_repr: [default: truncate] [currently: truncate]
    : 'truncate'/'info'

            For DataFrames exceeding max_rows/max_cols, the repr (and HTML repr) can
            show a truncated table (the default from 0.13), or switch to the view from
            df.info() (the behaviour in earlier versions of pandas).
    display.line_width: [default: 80] [currently: 80]
    : int
            Deprecated.
    	(Deprecated, use `display.width` instead.)

    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.  In case
            python/IPython is running in a terminal this can be set to 0 and pandas
            will correctly auto-detect the width the terminal and swap to a smaller
            format in case all columns would not fit vertically. The IPython notebook,
            IPython qtconsole, or IDLE do not run in a terminal and hence it is not
            possible to do correct auto-detection.
            'None' value means unlimited.
    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: 1690785] [currently: 1690785]
    : int or None
            df.info() will usually show null-counts for each column.
            For large frames this can be quite slow. max_info_rows and max_info_cols
            limit this null check only to frames with smaller dimensions then specified.
    display.max_rows: [default: 60] [currently: 60]
    : 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 a summary repr.
            'None' value means unlimited.
    display.max_seq_items: [default: 100] [currently: 100]
    : int or None

            when pretty-printing a long sequence, no more then `max_seq_items`
            will be printed. If items are omitted, 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.mpl_style: [default: None] [currently: None]
    : bool

            Setting this to 'default' will modify the rcParams used by matplotlib
            to give plots a more pleasing visual style by default.
            Setting this to None/False restores the values to their initial value.
    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
    display.show_dimensions: [default: True] [currently: True]
    : boolean
            Whether to print out dimensions at the end of DataFrame repr.
    display.width: [default: 80] [currently: 80]
    : int
            Width of the display in characters. In case python/IPython is running in
            a terminal this can be set to None and pandas will correctly auto-detect
            the width.
            Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a
            terminal and hence it is not possible to correctly detect the width.
    io.excel.xls.writer: [default: xlwt] [currently: xlwt]
    : string
            The default Excel writer engine for 'xls' files. Available options:
            'xlwt' (the default).
    io.excel.xlsm.writer: [default: openpyxl] [currently: openpyxl]
    : string
            The default Excel writer engine for 'xlsm' files. Available options:
            'openpyxl' (the default).
    io.excel.xlsx.writer: [default: xlsxwriter] [currently: xlsxwriter]
    : string
            The default Excel writer engine for 'xlsx' files. Available options:
            'xlsxwriter' (the default), 'openpyxl'.
    io.hdf.default_format: [default: None] [currently: None]
    : format
            default format writing format, if None, then
            put will default to 'fixed' and append will default to 'table'
    io.hdf.dropna_table: [default: True] [currently: True]
    : boolean
            drop ALL nan rows when appending to a table
    mode.chained_assignment: [default: warn] [currently: warn]
    : string
            Raise an exception, warn, or no action if trying to use chained assignment,
            The default is warn
    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 [282]: 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 [283]: get_option("display.max_rows")
    Out[283]: 60

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

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

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

    In [287]: get_option("display.max_rows")
    Out[287]: 60

It’s also possible to reset multiple options at once (using a regex):

    In [288]: reset_option("^display")

New in version 0.13.1.

    In [289]: with option_context("display.max_rows",10,"display.max_columns", 5):
       .....:    print get_option("display.max_rows")
       .....:
    10

    In [290]: print get_option("display.max_columns")
    20

    In [291]: print get_option("display.max_rows")
    60

    In [292]: print get_option("display.max_columns")
    20

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

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

    In [295]: s/1.e3
    Out[295]:
    a   -184.526u
    b   -615.011u
    c    104.861u
    d   -524.434u
    e      5.385u
    dtype: float64

    In [296]: s/1.e6
    Out[296]:
    a   -184.526n
    b   -615.011n
    c    104.861n
    d   -524.434n
    e      5.385n
    dtype: float64

The `set_printoptions` function has a number of options for controlling how floating point numbers are formatted (using the `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.

### Navigation

- index
- modules |
- next |
- previous |
- pandas 0.13.1 documentation »