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:

  1. In [1]: index = pd.date_range('1/1/2000', periods=8)
  2. In [2]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
  3. In [3]: df = pd.DataFrame(np.random.randn(8, 3), index=index,
  4. ...: columns=['A', 'B', 'C'])
  5. ...:
  6. In [4]: wp = pd.Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'],
  7. ...: major_axis=pd.date_range('1/1/2000', periods=5),
  8. ...: minor_axis=['A', 'B', 'C', 'D'])
  9. ...:

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.

  1. In [5]: long_series = pd.Series(np.random.randn(1000))
  2. In [6]: long_series.head()
  3. Out[6]:
  4. 0 -2.211372
  5. 1 0.974466
  6. 2 -2.006747
  7. 3 -0.410001
  8. 4 -0.078638
  9. dtype: float64
  10. In [7]: long_series.tail(3)
  11. Out[7]:
  12. 997 -0.196166
  13. 998 0.380733
  14. 999 -0.275874
  15. dtype: float64

Attributes and Underlying Data

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!

  1. In [8]: df[:2]
  2. Out[8]:
  3. A B C
  4. 2000-01-01 -0.173215 0.119209 -1.044236
  5. 2000-01-02 -0.861849 -2.104569 -0.494929
  6. In [9]: df.columns = [x.lower() for x in df.columns]
  7. In [10]: df
  8. Out[10]:
  9. a b c
  10. 2000-01-01 -0.173215 0.119209 -1.044236
  11. 2000-01-02 -0.861849 -2.104569 -0.494929
  12. 2000-01-03 1.071804 0.721555 -0.706771
  13. 2000-01-04 -1.039575 0.271860 -0.424972
  14. 2000-01-05 0.567020 0.276232 -1.087401
  15. 2000-01-06 -0.673690 0.113648 -1.478427
  16. 2000-01-07 0.524988 0.404705 0.577046
  17. 2000-01-08 -1.715002 -1.039268 -0.370647

Pandas objects (Index, Series, DataFrame) can be thought of as containers for arrays, which hold the actual data and do the actual computation. For many types, the underlying array is a numpy.ndarray. However, pandas and 3rd party libraries may extend NumPy’s type system to add support for custom arrays (see dtypes).

To get the actual data inside a Index or Series, use the .array property

  1. In [11]: s.array
  2. Out[11]:
  3. <PandasArray>
  4. [ 0.46911229990718628, -0.28286334432866328, -1.5090585031735124,
  5. -1.1356323710171934, 1.2121120250208506]
  6. Length: 5, dtype: float64
  7. In [12]: s.index.array
  8. Out[12]:
  9. <PandasArray>
  10. ['a', 'b', 'c', 'd', 'e']
  11. Length: 5, dtype: object

array will always be an ExtensionArray. The exact details of what an ExtensionArray is and why pandas uses them is a bit beyond the scope of this introduction. See dtypes for more.

If you know you need a NumPy array, use to_numpy() or numpy.asarray().

  1. In [13]: s.to_numpy()
  2. Out[13]: array([ 0.4691, -0.2829, -1.5091, -1.1356, 1.2121])
  3. In [14]: np.asarray(s)
  4. Out[14]: array([ 0.4691, -0.2829, -1.5091, -1.1356, 1.2121])

When the Series or Index is backed by an ExtensionArray, to_numpy() may involve copying data and coercing values. See dtypes for more.

to_numpy() gives some control over the dtype of the resulting numpy.ndarray. For example, consider datetimes with timezones. NumPy doesn’t have a dtype to represent timezone-aware datetimes, so there are two possibly useful representations:

  1. An object-dtype numpy.ndarray with Timestamp objects, each with the correct tz
  2. A datetime64[ns] -dtype numpy.ndarray, where the values have been converted to UTC and the timezone discarded

Timezones may be preserved with dtype=object

  1. In [15]: ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
  2. In [16]: ser.to_numpy(dtype=object)
  3. Out[16]:
  4. array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),
  5. Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')], dtype=object)

Or thrown away with dtype='datetime64[ns]'

  1. In [17]: ser.to_numpy(dtype="datetime64[ns]")
  2. Out[17]: array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'], dtype='datetime64[ns]')

Getting the “raw data” inside a DataFrame is possibly a bit more complex. When your DataFrame only has a single data type for all the columns, DataFrame.to_numpy() will return the underlying data:

  1. In [18]: df.to_numpy()
  2. Out[18]:
  3. array([[-0.1732, 0.1192, -1.0442],
  4. [-0.8618, -2.1046, -0.4949],
  5. [ 1.0718, 0.7216, -0.7068],
  6. [-1.0396, 0.2719, -0.425 ],
  7. [ 0.567 , 0.2762, -1.0874],
  8. [-0.6737, 0.1136, -1.4784],
  9. [ 0.525 , 0.4047, 0.577 ],
  10. [-1.715 , -1.0393, -0.3706]])

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.

::: tip 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. :::

In the past, pandas recommended Series.values or DataFrame.values for extracting the data from a Series or DataFrame. You’ll still find references to these in old code bases and online. Going forward, we recommend avoiding .values and using .array or .to_numpy(). .values has the following drawbacks:

  1. When your Series contains an extension type, it’s unclear whether Series.values returns a NumPy array or the extension array. Series.array will always return an ExtensionArray, and will never copy data. Series.to_numpy() will always return a NumPy array, potentially at the cost of copying / coercing values.
  2. When your DataFrame contains a mixture of data types, DataFrame.values may involve copying data and coercing values to a common dtype, a relatively expensive operation. DataFrame.to_numpy(), being a method, makes it clearer that the returned NumPy array may not be a view on the same data in the DataFrame.

Accelerated operations

pandas has support for accelerating certain types of binary numerical and boolean operations using the numexpr library 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.

These are both enabled to be used by default, you can control this by setting the options:

New in version 0.20.0.

  1. pd.set_option('compute.use_bottleneck', False)
  2. pd.set_option('compute.use_numexpr', False)

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:

  1. In [19]: df = pd.DataFrame({
  2. ....: 'one': pd.Series(np.random.randn(3), index=['a', 'b', 'c']),
  3. ....: 'two': pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),
  4. ....: 'three': pd.Series(np.random.randn(3), index=['b', 'c', 'd'])})
  5. ....:
  6. In [20]: df
  7. Out[20]:
  8. one two three
  9. a 1.400810 -1.643041 NaN
  10. b -0.356470 1.045911 0.395023
  11. c 0.797268 0.924515 -0.007090
  12. d NaN 1.553693 -1.670830
  13. In [21]: row = df.iloc[1]
  14. In [22]: column = df['two']
  15. In [23]: df.sub(row, axis='columns')
  16. Out[23]:
  17. one two three
  18. a 1.757280 -2.688953 NaN
  19. b 0.000000 0.000000 0.000000
  20. c 1.153738 -0.121396 -0.402113
  21. d NaN 0.507782 -2.065853
  22. In [24]: df.sub(row, axis=1)
  23. Out[24]:
  24. one two three
  25. a 1.757280 -2.688953 NaN
  26. b 0.000000 0.000000 0.000000
  27. c 1.153738 -0.121396 -0.402113
  28. d NaN 0.507782 -2.065853
  29. In [25]: df.sub(column, axis='index')
  30. Out[25]:
  31. one two three
  32. a 3.043851 0.0 NaN
  33. b -1.402381 0.0 -0.650888
  34. c -0.127247 0.0 -0.931605
  35. d NaN 0.0 -3.224524
  36. In [26]: df.sub(column, axis=0)
  37. Out[26]:
  38. one two three
  39. a 3.043851 0.0 NaN
  40. b -1.402381 0.0 -0.650888
  41. c -0.127247 0.0 -0.931605
  42. d NaN 0.0 -3.224524

Furthermore you can align a level of a MultiIndexed DataFrame with a Series.

  1. In [27]: dfmi = df.copy()
  2. In [28]: dfmi.index = pd.MultiIndex.from_tuples([(1, 'a'), (1, 'b'),
  3. ....: (1, 'c'), (2, 'a')],
  4. ....: names=['first', 'second'])
  5. ....:
  6. In [29]: dfmi.sub(column, axis=0, level='second')
  7. Out[29]:
  8. one two three
  9. first second
  10. 1 a 3.043851 0.000000 NaN
  11. b -1.402381 0.000000 -0.650888
  12. c -0.127247 0.000000 -0.931605
  13. 2 a NaN 3.196734 -0.027789

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:

  1. In [30]: major_mean = wp.mean(axis='major')
  2. In [31]: major_mean
  3. Out[31]:
  4. Item1 Item2
  5. A -0.378069 0.675929
  6. B -0.241429 -0.018080
  7. C -0.597702 0.129006
  8. D 0.204005 0.245570
  9. In [32]: wp.sub(major_mean, axis='major')
  10. Out[32]:
  11. <class 'pandas.core.panel.Panel'>
  12. Dimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)
  13. Items axis: Item1 to Item2
  14. Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
  15. Minor_axis axis: A to D

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

::: tip 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… :::

Series and Index also support the divmod() builtin. This function takes the floor division and modulo operation at the same time returning a two-tuple of the same type as the left hand side. For example:

  1. In [33]: s = pd.Series(np.arange(10))
  2. In [34]: s
  3. Out[34]:
  4. 0 0
  5. 1 1
  6. 2 2
  7. 3 3
  8. 4 4
  9. 5 5
  10. 6 6
  11. 7 7
  12. 8 8
  13. 9 9
  14. dtype: int64
  15. In [35]: div, rem = divmod(s, 3)
  16. In [36]: div
  17. Out[36]:
  18. 0 0
  19. 1 0
  20. 2 0
  21. 3 1
  22. 4 1
  23. 5 1
  24. 6 2
  25. 7 2
  26. 8 2
  27. 9 3
  28. dtype: int64
  29. In [37]: rem
  30. Out[37]:
  31. 0 0
  32. 1 1
  33. 2 2
  34. 3 0
  35. 4 1
  36. 5 2
  37. 6 0
  38. 7 1
  39. 8 2
  40. 9 0
  41. dtype: int64
  42. In [38]: idx = pd.Index(np.arange(10))
  43. In [39]: idx
  44. Out[39]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')
  45. In [40]: div, rem = divmod(idx, 3)
  46. In [41]: div
  47. Out[41]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2, 3], dtype='int64')
  48. In [42]: rem
  49. Out[42]: Int64Index([0, 1, 2, 0, 1, 2, 0, 1, 2, 0], dtype='int64')
  50. We can also do elementwise divmod():
  51. In [43]: div, rem = divmod(s, [2, 2, 3, 3, 4, 4, 5, 5, 6, 6])
  52. In [44]: div
  53. Out[44]:
  54. 0 0
  55. 1 0
  56. 2 0
  57. 3 1
  58. 4 1
  59. 5 1
  60. 6 1
  61. 7 1
  62. 8 1
  63. 9 1
  64. dtype: int64
  65. In [45]: rem
  66. Out[45]:
  67. 0 0
  68. 1 1
  69. 2 2
  70. 3 0
  71. 4 0
  72. 5 1
  73. 6 1
  74. 7 2
  75. 8 2
  76. 9 3
  77. dtype: int64

Missing data / operations with fill values

In Series and DataFrame, 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).

  1. In [46]: df
  2. Out[46]:
  3. one two three
  4. a 1.400810 -1.643041 NaN
  5. b -0.356470 1.045911 0.395023
  6. c 0.797268 0.924515 -0.007090
  7. d NaN 1.553693 -1.670830
  8. In [47]: df2
  9. Out[47]:
  10. one two three
  11. a 1.400810 -1.643041 1.000000
  12. b -0.356470 1.045911 0.395023
  13. c 0.797268 0.924515 -0.007090
  14. d NaN 1.553693 -1.670830
  15. In [48]: df + df2
  16. Out[48]:
  17. one two three
  18. a 2.801620 -3.286083 NaN
  19. b -0.712940 2.091822 0.790046
  20. c 1.594536 1.849030 -0.014180
  21. d NaN 3.107386 -3.341661
  22. In [49]: df.add(df2, fill_value=0)
  23. Out[49]:
  24. one two three
  25. a 2.801620 -3.286083 1.000000
  26. b -0.712940 2.091822 0.790046
  27. c 1.594536 1.849030 -0.014180
  28. d NaN 3.107386 -3.341661

Flexible Comparisons

Series and DataFrame have the binary comparison methods eq, ne, lt, gt, le, and ge whose behavior is analogous to the binary arithmetic operations described above:

  1. In [50]: df.gt(df2)
  2. Out[50]:
  3. one two three
  4. a False False False
  5. b False False False
  6. c False False False
  7. d False False False
  8. In [51]: df2.ne(df)
  9. Out[51]:
  10. one two three
  11. a False False True
  12. b False False False
  13. c False False False
  14. d True False False

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

Boolean Reductions

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

  1. In [52]: (df > 0).all()
  2. Out[52]:
  3. one False
  4. two False
  5. three False
  6. dtype: bool
  7. In [53]: (df > 0).any()
  8. Out[53]:
  9. one True
  10. two True
  11. three True
  12. dtype: bool

You can reduce to a final boolean value.

  1. In [54]: (df > 0).any().any()
  2. Out[54]: True

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

  1. In [55]: df.empty
  2. Out[55]: False
  3. In [56]: pd.DataFrame(columns=list('ABC')).empty
  4. Out[56]: True

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

  1. In [57]: pd.Series([True]).bool()
  2. Out[57]: True
  3. In [58]: pd.Series([False]).bool()
  4. Out[58]: False
  5. In [59]: pd.DataFrame([[True]]).bool()
  6. Out[59]: True
  7. In [60]: pd.DataFrame([[False]]).bool()
  8. Out[60]: False

::: Warning Warning

You might be tempted to do the following:

  1. >>> if df:
  2. ... pass

Or

  1. >>> df and df2

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

  1. 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 that 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:

  1. In [61]: df + df == df * 2
  2. Out[61]:
  3. one two three
  4. a True True False
  5. b True True True
  6. c True True True
  7. d False True True
  8. In [62]: (df + df == df * 2).all()
  9. Out[62]:
  10. one False
  11. two True
  12. three False
  13. dtype: bool

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

  1. In [63]: np.nan == np.nan
  2. Out[63]: False

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

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

Note that the Series or DataFrame index needs to be in the same order for equality to be True:

  1. In [65]: df1 = pd.DataFrame({'col': ['foo', 0, np.nan]})
  2. In [66]: df2 = pd.DataFrame({'col': [np.nan, 0, 'foo']}, index=[2, 1, 0])
  3. In [67]: df1.equals(df2)
  4. Out[67]: False
  5. In [68]: df1.equals(df2.sort_index())
  6. Out[68]: True

Comparing array-like objects

You can conveniently perform element-wise comparisons when comparing a pandas data structure with a scalar value:

  1. In [69]: pd.Series(['foo', 'bar', 'baz']) == 'foo'
  2. Out[69]:
  3. 0 True
  4. 1 False
  5. 2 False
  6. dtype: bool
  7. In [70]: pd.Index(['foo', 'bar', 'baz']) == 'foo'
  8. Out[70]: array([ True, False, False], dtype=bool)

Pandas also handles element-wise comparisons between different array-like objects of the same length:

  1. In [71]: pd.Series(['foo', 'bar', 'baz']) == pd.Index(['foo', 'bar', 'qux'])
  2. Out[71]:
  3. 0 True
  4. 1 True
  5. 2 False
  6. dtype: bool
  7. In [72]: pd.Series(['foo', 'bar', 'baz']) == np.array(['foo', 'bar', 'qux'])
  8. Out[72]:
  9. 0 True
  10. 1 True
  11. 2 False
  12. dtype: bool

Trying to compare Index or Series objects of different lengths will raise a ValueError:

  1. In [55]: pd.Series(['foo', 'bar', 'baz']) == pd.Series(['foo', 'bar'])
  2. ValueError: Series lengths must match to compare
  3. In [56]: pd.Series(['foo', 'bar', 'baz']) == pd.Series(['foo'])
  4. ValueError: Series lengths must match to compare

Note that this is different from the NumPy behavior where a comparison can be broadcast:

  1. In [73]: np.array([1, 2, 3]) == np.array([2])
  2. Out[73]: array([False, True, False], dtype=bool)

or it can return False if broadcasting can not be done:

  1. In [74]: np.array([1, 2, 3]) == np.array([1, 2])
  2. Out[74]: 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:

  1. In [75]: df1 = pd.DataFrame({'A': [1., np.nan, 3., 5., np.nan],
  2. ....: 'B': [np.nan, 2., 3., np.nan, 6.]})
  3. ....:
  4. In [76]: df2 = pd.DataFrame({'A': [5., 2., 4., np.nan, 3., 7.],
  5. ....: 'B': [np.nan, np.nan, 3., 4., 6., 8.]})
  6. ....:
  7. In [77]: df1
  8. Out[77]:
  9. A B
  10. 0 1.0 NaN
  11. 1 NaN 2.0
  12. 2 3.0 3.0
  13. 3 5.0 NaN
  14. 4 NaN 6.0
  15. In [78]: df2
  16. Out[78]:
  17. A B
  18. 0 5.0 NaN
  19. 1 2.0 NaN
  20. 2 4.0 3.0
  21. 3 NaN 4.0
  22. 4 3.0 6.0
  23. 5 7.0 8.0
  24. In [79]: df1.combine_first(df2)
  25. Out[79]:
  26. A B
  27. 0 1.0 NaN
  28. 1 2.0 2.0
  29. 2 3.0 3.0
  30. 3 5.0 4.0
  31. 4 3.0 6.0
  32. 5 7.0 8.0

General DataFrame Combine

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

So, for instance, to reproduce combine_first() as above:

  1. In [80]: def combiner(x, y):
  2. ....: return np.where(pd.isna(x), y, x)
  3. ....:

Descriptive statistics

There exists 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:

  1. In [81]: df
  2. Out[81]:
  3. one two three
  4. a 1.400810 -1.643041 NaN
  5. b -0.356470 1.045911 0.395023
  6. c 0.797268 0.924515 -0.007090
  7. d NaN 1.553693 -1.670830
  8. In [82]: df.mean(0)
  9. Out[82]:
  10. one 0.613869
  11. two 0.470270
  12. three -0.427633
  13. dtype: float64
  14. In [83]: df.mean(1)
  15. Out[83]:
  16. a -0.121116
  17. b 0.361488
  18. c 0.571564
  19. d -0.058569
  20. dtype: float64

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

  1. In [84]: df.sum(0, skipna=False)
  2. Out[84]:
  3. one NaN
  4. two 1.881078
  5. three NaN
  6. dtype: float64
  7. In [85]: df.sum(axis=1, skipna=True)
  8. Out[85]:
  9. a -0.242232
  10. b 1.084464
  11. c 1.714693
  12. d -0.117137
  13. 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:

  1. In [86]: ts_stand = (df - df.mean()) / df.std()
  2. In [87]: ts_stand.std()
  3. Out[87]:
  4. one 1.0
  5. two 1.0
  6. three 1.0
  7. dtype: float64
  8. In [88]: xs_stand = df.sub(df.mean(1), axis=0).div(df.std(1), axis=0)
  9. In [89]: xs_stand.std(1)
  10. Out[89]:
  11. a 1.0
  12. b 1.0
  13. c 1.0
  14. d 1.0
  15. dtype: float64

Note that methods like cumsum() and cumprod() preserve the location of NaN values. This is somewhat different from expanding() and rolling(). For more details please see this note.

  1. In [90]: df.cumsum()
  2. Out[90]:
  3. one two three
  4. a 1.400810 -1.643041 NaN
  5. b 1.044340 -0.597130 0.395023
  6. c 1.841608 0.327385 0.387933
  7. d NaN 1.881078 -1.282898

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-NA 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 Bessel-corrected sample standard deviation
var Unbiased variance
sem Standard error of the mean
skew Sample skewness (3rd moment)
kurt Sample 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:

  1. In [91]: np.mean(df['one'])
  2. Out[91]: 0.6138692844180106
  3. In [92]: np.mean(df['one'].to_numpy())
  4. Out[92]: nan

Series.nunique() will return the number of unique non-NA values in a Series:

  1. In [93]: series = pd.Series(np.random.randn(500))
  2. In [94]: series[20:500] = np.nan
  3. In [95]: series[10:20] = 5
  4. In [96]: series.nunique()
  5. Out[96]: 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):

  1. In [97]: series = pd.Series(np.random.randn(1000))
  2. In [98]: series[::2] = np.nan
  3. In [99]: series.describe()
  4. Out[99]:
  5. count 500.000000
  6. mean -0.020695
  7. std 1.011840
  8. min -2.683763
  9. 25% -0.709297
  10. 50% -0.070211
  11. 75% 0.712856
  12. max 3.160915
  13. dtype: float64
  14. In [100]: frame = pd.DataFrame(np.random.randn(1000, 5),
  15. .....: columns=['a', 'b', 'c', 'd', 'e'])
  16. .....:
  17. In [101]: frame.iloc[::2] = np.nan
  18. In [102]: frame.describe()
  19. Out[102]:
  20. a b c d e
  21. count 500.000000 500.000000 500.000000 500.000000 500.000000
  22. mean 0.026515 0.022952 -0.047307 -0.052551 0.011210
  23. std 1.016752 0.980046 1.020837 1.008271 1.006726
  24. min -3.000951 -2.637901 -3.303099 -3.159200 -3.188821
  25. 25% -0.647623 -0.593587 -0.709906 -0.691338 -0.689176
  26. 50% 0.047578 -0.026675 -0.029655 -0.032769 -0.015775
  27. 75% 0.723946 0.771931 0.603753 0.667044 0.652221
  28. max 2.740139 2.752332 3.004229 2.728702 3.240991

You can select specific percentiles to include in the output:

  1. In [103]: series.describe(percentiles=[.05, .25, .75, .95])
  2. Out[103]:
  3. count 500.000000
  4. mean -0.020695
  5. std 1.011840
  6. min -2.683763
  7. 5% -1.641337
  8. 25% -0.709297
  9. 50% -0.070211
  10. 75% 0.712856
  11. 95% 1.699176
  12. max 3.160915
  13. dtype: float64

By default, the median is always included.

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

  1. In [104]: s = pd.Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])
  2. In [105]: s.describe()
  3. Out[105]:
  4. count 9
  5. unique 4
  6. top a
  7. freq 5
  8. dtype: object

Note that on a mixed-type DataFrame object, describe() will restrict the summary to include only numerical columns or, if none are, only categorical columns:

  1. In [106]: frame = pd.DataFrame({'a': ['Yes', 'Yes', 'No', 'No'], 'b': range(4)})
  2. In [107]: frame.describe()
  3. Out[107]:
  4. b
  5. count 4.000000
  6. mean 1.500000
  7. std 1.290994
  8. min 0.000000
  9. 25% 0.750000
  10. 50% 1.500000
  11. 75% 2.250000
  12. max 3.000000

This behavior can be controlled by providing a list of types as include/exclude arguments. The special value all can also be used:

  1. In [108]: frame.describe(include=['object'])
  2. Out[108]:
  3. a
  4. count 4
  5. unique 2
  6. top Yes
  7. freq 2
  8. In [109]: frame.describe(include=['number'])
  9. Out[109]:
  10. b
  11. count 4.000000
  12. mean 1.500000
  13. std 1.290994
  14. min 0.000000
  15. 25% 0.750000
  16. 50% 1.500000
  17. 75% 2.250000
  18. max 3.000000
  19. In [110]: frame.describe(include='all')
  20. Out[110]:
  21. a b
  22. count 4 4.000000
  23. unique 2 NaN
  24. top Yes NaN
  25. freq 2 NaN
  26. mean NaN 1.500000
  27. std NaN 1.290994
  28. min NaN 0.000000
  29. 25% NaN 0.750000
  30. 50% NaN 1.500000
  31. 75% NaN 2.250000
  32. max NaN 3.000000

That feature relies on select_dtypes. Refer to there for details about accepted inputs.

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:

  1. In [111]: s1 = pd.Series(np.random.randn(5))
  2. In [112]: s1
  3. Out[112]:
  4. 0 -0.068822
  5. 1 -1.129788
  6. 2 -0.269798
  7. 3 -0.375580
  8. 4 0.513381
  9. dtype: float64
  10. In [113]: s1.idxmin(), s1.idxmax()
  11. Out[113]: (1, 4)
  12. In [114]: df1 = pd.DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])
  13. In [115]: df1
  14. Out[115]:
  15. A B C
  16. 0 0.333329 -0.910090 -1.321220
  17. 1 2.111424 1.701169 0.858336
  18. 2 -0.608055 -2.082155 -0.069618
  19. 3 1.412817 -0.562658 0.770042
  20. 4 0.373294 -0.965381 -1.607840
  21. In [116]: df1.idxmin(axis=0)
  22. Out[116]:
  23. A 2
  24. B 2
  25. C 4
  26. dtype: int64
  27. In [117]: df1.idxmax(axis=1)
  28. Out[117]:
  29. 0 A
  30. 1 A
  31. 2 C
  32. 3 A
  33. 4 A
  34. dtype: object

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

  1. In [118]: df3 = pd.DataFrame([2, 1, 1, 3, np.nan], columns=['A'], index=list('edcba'))
  2. In [119]: df3
  3. Out[119]:
  4. A
  5. e 2.0
  6. d 1.0
  7. c 1.0
  8. b 3.0
  9. a NaN
  10. In [120]: df3['A'].idxmin()
  11. Out[120]: 'd'

::: tip 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:

  1. In [121]: data = np.random.randint(0, 7, size=50)
  2. In [122]: data
  3. Out[122]:
  4. array([6, 4, 1, 3, 4, 4, 4, 6, 5, 2, 6, 1, 0, 4, 3, 2, 5, 3, 4, 0, 5, 3, 0,
  5. 1, 5, 0, 1, 5, 3, 4, 1, 2, 3, 2, 4, 6, 1, 4, 3, 5, 2, 1, 2, 4, 1, 6,
  6. 3, 6, 3, 3])
  7. In [123]: s = pd.Series(data)
  8. In [124]: s.value_counts()
  9. Out[124]:
  10. 4 10
  11. 3 10
  12. 1 8
  13. 6 6
  14. 5 6
  15. 2 6
  16. 0 4
  17. dtype: int64
  18. In [125]: pd.value_counts(data)
  19. Out[125]:
  20. 4 10
  21. 3 10
  22. 1 8
  23. 6 6
  24. 5 6
  25. 2 6
  26. 0 4
  27. dtype: int64

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

  1. In [126]: s5 = pd.Series([1, 1, 3, 3, 3, 5, 5, 7, 7, 7])
  2. In [127]: s5.mode()
  3. Out[127]:
  4. 0 3
  5. 1 7
  6. dtype: int64
  7. In [128]: df5 = pd.DataFrame({"A": np.random.randint(0, 7, size=50),
  8. .....: "B": np.random.randint(-10, 15, size=50)})
  9. .....:
  10. In [129]: df5.mode()
  11. Out[129]:
  12. A B
  13. 0 0 -9

Discretization and quantiling

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

  1. In [130]: arr = np.random.randn(20)
  2. In [131]: factor = pd.cut(arr, 4)
  3. In [132]: factor
  4. Out[132]:
  5. [(1.27, 2.31], (0.231, 1.27], (-0.809, 0.231], (-1.853, -0.809], (1.27, 2.31], ..., (0.231, 1.27], (-0.809, 0.231], (-1.853, -0.809], (1.27, 2.31], (0.231, 1.27]]
  6. Length: 20
  7. Categories (4, interval[float64]): [(-1.853, -0.809] < (-0.809, 0.231] < (0.231, 1.27] < (1.27, 2.31]]
  8. In [133]: factor = pd.cut(arr, [-5, -1, 0, 1, 5])
  9. In [134]: factor
  10. Out[134]:
  11. [(1, 5], (0, 1], (-1, 0], (-5, -1], (1, 5], ..., (1, 5], (-1, 0], (-5, -1], (1, 5], (0, 1]]
  12. Length: 20
  13. Categories (4, interval[int64]): [(-5, -1] < (-1, 0] < (0, 1] < (1, 5]]

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

  1. In [135]: arr = np.random.randn(30)
  2. In [136]: factor = pd.qcut(arr, [0, .25, .5, .75, 1])
  3. In [137]: factor
  4. Out[137]:
  5. [(-2.219, -0.669], (-0.669, 0.00453], (0.367, 2.369], (0.00453, 0.367], (0.367, 2.369], ..., (0.00453, 0.367], (0.367, 2.369], (0.00453, 0.367], (-0.669, 0.00453], (0.367, 2.369]]
  6. Length: 30
  7. Categories (4, interval[float64]): [(-2.219, -0.669] < (-0.669, 0.00453] < (0.00453, 0.367] <
  8. (0.367, 2.369]]
  9. In [138]: pd.value_counts(factor)
  10. Out[138]:
  11. (0.367, 2.369] 8
  12. (-2.219, -0.669] 8
  13. (0.00453, 0.367] 7
  14. (-0.669, 0.00453] 7
  15. dtype: int64

We can also pass infinite values to define the bins:

  1. In [139]: arr = np.random.randn(20)
  2. In [140]: factor = pd.cut(arr, [-np.inf, 0, np.inf])
  3. In [141]: factor
  4. Out[141]:
  5. [(0.0, inf], (-inf, 0.0], (-inf, 0.0], (-inf, 0.0], (-inf, 0.0], ..., (-inf, 0.0], (-inf, 0.0], (0.0, inf], (-inf, 0.0], (-inf, 0.0]]
  6. Length: 20
  7. Categories (2, interval[float64]): [(-inf, 0.0] < (0.0, inf]]

Function application

To apply your own or another library’s functions to pandas objects, you should be aware of the three methods below. The appropriate method to use depends on whether your function expects to operate on an entire DataFrame or Series, row- or column-wise, or elementwise.

  1. Tablewise Function Application: pipe()
  2. Row or Column-wise Function Application: apply()
  3. Aggregation API: agg() and transform()
  4. Applying Elementwise Functions: applymap()

Tablewise Function Application

DataFrames and Series can of course just be passed into functions. However, if the function needs to be called in a chain, consider using the pipe() method. Compare the following

  1. # f, g, and h are functions taking and returning ``DataFrames``
  2. >>> f(g(h(df), arg1=1), arg2=2, arg3=3)

with the equivalent

  1. >>> (df.pipe(h)
  2. ... .pipe(g, arg1=1)
  3. ... .pipe(f, arg2=2, arg3=3))

Pandas encourages the second style, which is known as method chaining. pipe makes it easy to use your own or another library’s functions in method chains, alongside pandas’ methods.

In the example above, the functions f, g, and h each expected the DataFrame as the first positional argument. What if the function you wish to apply takes its data as, say, the second argument? In this case, provide pipe with a tuple of (callable, data_keyword). .pipe will route the DataFrame to the argument specified in the tuple.

For example, we can fit a regression using statsmodels. Their API expects a formula first and a DataFrame as the second argument, data. We pass in the function, keyword pair (sm.ols, 'data') to pipe:

  1. In [142]: import statsmodels.formula.api as sm
  2. In [143]: bb = pd.read_csv('data/baseball.csv', index_col='id')
  3. In [144]: (bb.query('h > 0')
  4. .....: .assign(ln_h=lambda df: np.log(df.h))
  5. .....: .pipe((sm.ols, 'data'), 'hr ~ ln_h + year + g + C(lg)')
  6. .....: .fit()
  7. .....: .summary()
  8. .....: )
  9. .....:
  10. Out[144]:
  11. <class 'statsmodels.iolib.summary.Summary'>
  12. """
  13. OLS Regression Results
  14. ==============================================================================
  15. Dep. Variable: hr R-squared: 0.685
  16. Model: OLS Adj. R-squared: 0.665
  17. Method: Least Squares F-statistic: 34.28
  18. Date: Tue, 12 Mar 2019 Prob (F-statistic): 3.48e-15
  19. Time: 22:38:35 Log-Likelihood: -205.92
  20. No. Observations: 68 AIC: 421.8
  21. Df Residuals: 63 BIC: 432.9
  22. Df Model: 4
  23. Covariance Type: nonrobust
  24. ===============================================================================
  25. coef std err t P>|t| [0.025 0.975]
  26. -------------------------------------------------------------------------------
  27. Intercept -8484.7720 4664.146 -1.819 0.074 -1.78e+04 835.780
  28. C(lg)[T.NL] -2.2736 1.325 -1.716 0.091 -4.922 0.375
  29. ln_h -1.3542 0.875 -1.547 0.127 -3.103 0.395
  30. year 4.2277 2.324 1.819 0.074 -0.417 8.872
  31. g 0.1841 0.029 6.258 0.000 0.125 0.243
  32. ==============================================================================
  33. Omnibus: 10.875 Durbin-Watson: 1.999
  34. Prob(Omnibus): 0.004 Jarque-Bera (JB): 17.298
  35. Skew: 0.537 Prob(JB): 0.000175
  36. Kurtosis: 5.225 Cond. No. 1.49e+07
  37. ==============================================================================
  38. Warnings:
  39. [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
  40. [2] The condition number is large, 1.49e+07. This might indicate that there are
  41. strong multicollinearity or other numerical problems.
  42. """

The pipe method is inspired by unix pipes and more recently dplyr and magrittr, which have introduced the popular (%>%) (read pipe) operator for R. The implementation of pipe here is quite clean and feels right at home in python. We encourage you to view the source code of pipe().

Row or Column-wise Function Application

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

  1. In [145]: df.apply(np.mean)
  2. Out[145]:
  3. one 0.613869
  4. two 0.470270
  5. three -0.427633
  6. dtype: float64
  7. In [146]: df.apply(np.mean, axis=1)
  8. Out[146]:
  9. a -0.121116
  10. b 0.361488
  11. c 0.571564
  12. d -0.058569
  13. dtype: float64
  14. In [147]: df.apply(lambda x: x.max() - x.min())
  15. Out[147]:
  16. one 1.757280
  17. two 3.196734
  18. three 2.065853
  19. dtype: float64
  20. In [148]: df.apply(np.cumsum)
  21. Out[148]:
  22. one two three
  23. a 1.400810 -1.643041 NaN
  24. b 1.044340 -0.597130 0.395023
  25. c 1.841608 0.327385 0.387933
  26. d NaN 1.881078 -1.282898
  27. In [149]: df.apply(np.exp)
  28. Out[149]:
  29. one two three
  30. a 4.058485 0.193391 NaN
  31. b 0.700143 2.845991 1.484418
  32. c 2.219469 2.520646 0.992935
  33. d NaN 4.728902 0.188091

The apply() method will also dispatch on a string method name.

  1. In [150]: df.apply('mean')
  2. Out[150]:
  3. one 0.613869
  4. two 0.470270
  5. three -0.427633
  6. dtype: float64
  7. In [151]: df.apply('mean', axis=1)
  8. Out[151]:
  9. a -0.121116
  10. b 0.361488
  11. c 0.571564
  12. d -0.058569
  13. dtype: float64

The return type of the function passed to apply() affects the type of the final output from DataFrame.apply for the default behaviour:

  • If the applied function returns a Series, the final output is a DataFrame. The columns match the index of the Series returned by the applied function.
  • If the applied function returns any other type, the final output is a Series.

This default behaviour can be overridden using the result_type, which accepts three options: reduce, broadcast, and expand. These will determine how list-likes return values expand (or not) to a DataFrame.

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:

  1. In [152]: tsdf = pd.DataFrame(np.random.randn(1000, 3), columns=['A', 'B', 'C'],
  2. .....: index=pd.date_range('1/1/2000', periods=1000))
  3. .....:
  4. In [153]: tsdf.apply(lambda x: x.idxmax())
  5. Out[153]:
  6. A 2000-06-10
  7. B 2001-07-04
  8. C 2002-08-09
  9. 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:

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

You may then apply this function as follows:

  1. 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:

  1. In [154]: tsdf
  2. Out[154]:
  3. A B C
  4. 2000-01-01 -0.652077 -0.239118 0.841272
  5. 2000-01-02 0.130224 0.347505 -0.385666
  6. 2000-01-03 -1.700237 -0.925899 0.199564
  7. 2000-01-04 NaN NaN NaN
  8. 2000-01-05 NaN NaN NaN
  9. 2000-01-06 NaN NaN NaN
  10. 2000-01-07 NaN NaN NaN
  11. 2000-01-08 0.339319 -0.978307 0.689492
  12. 2000-01-09 0.601495 -0.630417 -1.040079
  13. 2000-01-10 1.511723 -0.427952 -0.400154
  14. In [155]: tsdf.apply(pd.Series.interpolate)
  15. Out[155]:
  16. A B C
  17. 2000-01-01 -0.652077 -0.239118 0.841272
  18. 2000-01-02 0.130224 0.347505 -0.385666
  19. 2000-01-03 -1.700237 -0.925899 0.199564
  20. 2000-01-04 -1.292326 -0.936380 0.297550
  21. 2000-01-05 -0.884415 -0.946862 0.395535
  22. 2000-01-06 -0.476503 -0.957344 0.493521
  23. 2000-01-07 -0.068592 -0.967825 0.591507
  24. 2000-01-08 0.339319 -0.978307 0.689492
  25. 2000-01-09 0.601495 -0.630417 -1.040079
  26. 2000-01-10 1.511723 -0.427952 -0.400154

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.

Aggregation API

New in version 0.20.0.

The aggregation API allows one to express possibly multiple aggregation operations in a single concise way. This API is similar across pandas objects, see groupby API, the window functions API, and the resample API. The entry point for aggregation is DataFrame.aggregate(), or the alias DataFrame.agg().

We will use a similar starting frame from above:

  1. In [156]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],
  2. .....: index=pd.date_range('1/1/2000', periods=10))
  3. .....:
  4. In [157]: tsdf.iloc[3:7] = np.nan
  5. In [158]: tsdf
  6. Out[158]:
  7. A B C
  8. 2000-01-01 0.396575 -0.364907 0.051290
  9. 2000-01-02 -0.310517 -0.369093 -0.353151
  10. 2000-01-03 -0.522441 1.659115 -0.272364
  11. 2000-01-04 NaN NaN NaN
  12. 2000-01-05 NaN NaN NaN
  13. 2000-01-06 NaN NaN NaN
  14. 2000-01-07 NaN NaN NaN
  15. 2000-01-08 -0.057890 1.148901 0.011528
  16. 2000-01-09 -0.155578 0.742150 0.107324
  17. 2000-01-10 0.531797 0.080254 0.833297

Using a single function is equivalent to papply(). You can also pass named methods as strings. These will return a Series of the aggregated output:

  1. In [159]: tsdf.agg(np.sum)
  2. Out[159]:
  3. A -0.118055
  4. B 2.896420
  5. C 0.377923
  6. dtype: float64
  7. In [160]: tsdf.agg('sum')
  8. Out[160]:
  9. A -0.118055
  10. B 2.896420
  11. C 0.377923
  12. dtype: float64
  13. # these are equivalent to a ``.sum()`` because we are aggregating
  14. # on a single function
  15. In [161]: tsdf.sum()
  16. Out[161]:
  17. A -0.118055
  18. B 2.896420
  19. C 0.377923
  20. dtype: float64

Single aggregations on a Series this will return a scalar value:

  1. In [162]: tsdf.A.agg('sum')
  2. Out[162]: -0.11805495013260869

Aggregating with multiple functions

You can pass multiple aggregation arguments as a list. The results of each of the passed functions will be a row in the resulting DataFrame. These are naturally named from the aggregation function.

  1. In [163]: tsdf.agg(['sum'])
  2. Out[163]:
  3. A B C
  4. sum -0.118055 2.89642 0.377923

Multiple functions yield multiple rows:

  1. In [164]: tsdf.agg(['sum', 'mean'])
  2. Out[164]:
  3. A B C
  4. sum -0.118055 2.896420 0.377923
  5. mean -0.019676 0.482737 0.062987

On a Series, multiple functions return a Series, indexed by the function names:

  1. In [165]: tsdf.A.agg(['sum', 'mean'])
  2. Out[165]:
  3. sum -0.118055
  4. mean -0.019676
  5. Name: A, dtype: float64

Passing a lambda function will yield a <lambda> named row:

  1. In [166]: tsdf.A.agg(['sum', lambda x: x.mean()])
  2. Out[166]:
  3. sum -0.118055
  4. <lambda> -0.019676
  5. Name: A, dtype: float64

Passing a named function will yield that name for the row:

  1. In [167]: def mymean(x):
  2. .....: return x.mean()
  3. .....:
  4. In [168]: tsdf.A.agg(['sum', mymean])
  5. Out[168]:
  6. sum -0.118055
  7. mymean -0.019676
  8. Name: A, dtype: float64

Aggregating with a dict

Passing a dictionary of column names to a scalar or a list of scalars, to DataFrame.agg allows you to customize which functions are applied to which columns. Note that the results are not in any particular order, you can use an OrderedDict instead to guarantee ordering.

  1. In [169]: tsdf.agg({'A': 'mean', 'B': 'sum'})
  2. Out[169]:
  3. A -0.019676
  4. B 2.896420
  5. dtype: float64

Passing a list-like will generate a DataFrame output. You will get a matrix-like output of all of the aggregators. The output will consist of all unique functions. Those that are not noted for a particular column will be NaN:

  1. In [170]: tsdf.agg({'A': ['mean', 'min'], 'B': 'sum'})
  2. Out[170]:
  3. A B
  4. mean -0.019676 NaN
  5. min -0.522441 NaN
  6. sum NaN 2.89642

Mixed Dtypes

When presented with mixed dtypes that cannot aggregate, .agg will only take the valid aggregations. This is similar to how groupby .agg works.

  1. In [171]: mdf = pd.DataFrame({'A': [1, 2, 3],
  2. .....: 'B': [1., 2., 3.],
  3. .....: 'C': ['foo', 'bar', 'baz'],
  4. .....: 'D': pd.date_range('20130101', periods=3)})
  5. .....:
  6. In [172]: mdf.dtypes
  7. Out[172]:
  8. A int64
  9. B float64
  10. C object
  11. D datetime64[ns]
  12. dtype: object
  1. In [173]: mdf.agg(['min', 'sum'])
  2. Out[173]:
  3. A B C D
  4. min 1 1.0 bar 2013-01-01
  5. sum 6 6.0 foobarbaz NaT

Custom describe

With .agg() is it possible to easily create a custom describe function, similar to the built in describe function.

  1. In [174]: from functools import partial
  2. In [175]: q_25 = partial(pd.Series.quantile, q=0.25)
  3. In [176]: q_25.__name__ = '25%'
  4. In [177]: q_75 = partial(pd.Series.quantile, q=0.75)
  5. In [178]: q_75.__name__ = '75%'
  6. In [179]: tsdf.agg(['count', 'mean', 'std', 'min', q_25, 'median', q_75, 'max'])
  7. Out[179]:
  8. A B C
  9. count 6.000000 6.000000 6.000000
  10. mean -0.019676 0.482737 0.062987
  11. std 0.408577 0.836785 0.420419
  12. min -0.522441 -0.369093 -0.353151
  13. 25% -0.271782 -0.253617 -0.201391
  14. median -0.106734 0.411202 0.031409
  15. 75% 0.282958 1.047213 0.093315
  16. max 0.531797 1.659115 0.833297

Transform API

New in version 0.20.0.

The transform() method returns an object that is indexed the same (same size) as the original. This API allows you to provide multiple operations at the same time rather than one-by-one. Its API is quite similar to the .agg API.

We create a frame similar to the one used in the above sections.

  1. In [180]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],
  2. .....: index=pd.date_range('1/1/2000', periods=10))
  3. .....:
  4. In [181]: tsdf.iloc[3:7] = np.nan
  5. In [182]: tsdf
  6. Out[182]:
  7. A B C
  8. 2000-01-01 -1.219234 -1.652700 -0.698277
  9. 2000-01-02 1.858653 -0.738520 0.630364
  10. 2000-01-03 -0.112596 1.525897 1.364225
  11. 2000-01-04 NaN NaN NaN
  12. 2000-01-05 NaN NaN NaN
  13. 2000-01-06 NaN NaN NaN
  14. 2000-01-07 NaN NaN NaN
  15. 2000-01-08 -0.527790 -1.715506 0.387274
  16. 2000-01-09 -0.569341 0.569386 0.134136
  17. 2000-01-10 -0.413993 -0.862280 0.662690

Transform the entire frame. .transform() allows input functions as: a NumPy function, a string function name or a user defined function.

  1. In [183]: tsdf.transform(np.abs)
  2. Out[183]:
  3. A B C
  4. 2000-01-01 1.219234 1.652700 0.698277
  5. 2000-01-02 1.858653 0.738520 0.630364
  6. 2000-01-03 0.112596 1.525897 1.364225
  7. 2000-01-04 NaN NaN NaN
  8. 2000-01-05 NaN NaN NaN
  9. 2000-01-06 NaN NaN NaN
  10. 2000-01-07 NaN NaN NaN
  11. 2000-01-08 0.527790 1.715506 0.387274
  12. 2000-01-09 0.569341 0.569386 0.134136
  13. 2000-01-10 0.413993 0.862280 0.662690
  14. In [184]: tsdf.transform('abs')
  15. Out[184]:
  16. A B C
  17. 2000-01-01 1.219234 1.652700 0.698277
  18. 2000-01-02 1.858653 0.738520 0.630364
  19. 2000-01-03 0.112596 1.525897 1.364225
  20. 2000-01-04 NaN NaN NaN
  21. 2000-01-05 NaN NaN NaN
  22. 2000-01-06 NaN NaN NaN
  23. 2000-01-07 NaN NaN NaN
  24. 2000-01-08 0.527790 1.715506 0.387274
  25. 2000-01-09 0.569341 0.569386 0.134136
  26. 2000-01-10 0.413993 0.862280 0.662690
  27. In [185]: tsdf.transform(lambda x: x.abs())
  28. Out[185]:
  29. A B C
  30. 2000-01-01 1.219234 1.652700 0.698277
  31. 2000-01-02 1.858653 0.738520 0.630364
  32. 2000-01-03 0.112596 1.525897 1.364225
  33. 2000-01-04 NaN NaN NaN
  34. 2000-01-05 NaN NaN NaN
  35. 2000-01-06 NaN NaN NaN
  36. 2000-01-07 NaN NaN NaN
  37. 2000-01-08 0.527790 1.715506 0.387274
  38. 2000-01-09 0.569341 0.569386 0.134136
  39. 2000-01-10 0.413993 0.862280 0.662690

Here transform() received a single function; this is equivalent to a ufunc application.

  1. In [186]: np.abs(tsdf)
  2. Out[186]:
  3. A B C
  4. 2000-01-01 1.219234 1.652700 0.698277
  5. 2000-01-02 1.858653 0.738520 0.630364
  6. 2000-01-03 0.112596 1.525897 1.364225
  7. 2000-01-04 NaN NaN NaN
  8. 2000-01-05 NaN NaN NaN
  9. 2000-01-06 NaN NaN NaN
  10. 2000-01-07 NaN NaN NaN
  11. 2000-01-08 0.527790 1.715506 0.387274
  12. 2000-01-09 0.569341 0.569386 0.134136
  13. 2000-01-10 0.413993 0.862280 0.662690

Passing a single function to .transform() with a Series will yield a single Series in return.

  1. In [187]: tsdf.A.transform(np.abs)
  2. Out[187]:
  3. 2000-01-01 1.219234
  4. 2000-01-02 1.858653
  5. 2000-01-03 0.112596
  6. 2000-01-04 NaN
  7. 2000-01-05 NaN
  8. 2000-01-06 NaN
  9. 2000-01-07 NaN
  10. 2000-01-08 0.527790
  11. 2000-01-09 0.569341
  12. 2000-01-10 0.413993
  13. Freq: D, Name: A, dtype: float64

Transform with multiple functions

Passing multiple functions will yield a column MultiIndexed DataFrame. The first level will be the original frame column names; the second level will be the names of the transforming functions.

  1. In [188]: tsdf.transform([np.abs, lambda x: x + 1])
  2. Out[188]:
  3. A B C
  4. absolute <lambda> absolute <lambda> absolute <lambda>
  5. 2000-01-01 1.219234 -0.219234 1.652700 -0.652700 0.698277 0.301723
  6. 2000-01-02 1.858653 2.858653 0.738520 0.261480 0.630364 1.630364
  7. 2000-01-03 0.112596 0.887404 1.525897 2.525897 1.364225 2.364225
  8. 2000-01-04 NaN NaN NaN NaN NaN NaN
  9. 2000-01-05 NaN NaN NaN NaN NaN NaN
  10. 2000-01-06 NaN NaN NaN NaN NaN NaN
  11. 2000-01-07 NaN NaN NaN NaN NaN NaN
  12. 2000-01-08 0.527790 0.472210 1.715506 -0.715506 0.387274 1.387274
  13. 2000-01-09 0.569341 0.430659 0.569386 1.569386 0.134136 1.134136
  14. 2000-01-10 0.413993 0.586007 0.862280 0.137720 0.662690 1.662690

Passing multiple functions to a Series will yield a DataFrame. The resulting column names will be the transforming functions.

  1. In [189]: tsdf.A.transform([np.abs, lambda x: x + 1])
  2. Out[189]:
  3. absolute <lambda>
  4. 2000-01-01 1.219234 -0.219234
  5. 2000-01-02 1.858653 2.858653
  6. 2000-01-03 0.112596 0.887404
  7. 2000-01-04 NaN NaN
  8. 2000-01-05 NaN NaN
  9. 2000-01-06 NaN NaN
  10. 2000-01-07 NaN NaN
  11. 2000-01-08 0.527790 0.472210
  12. 2000-01-09 0.569341 0.430659
  13. 2000-01-10 0.413993 0.586007

Transforming with a dict

Passing a dict of functions will allow selective transforming per column.

  1. In [190]: tsdf.transform({'A': np.abs, 'B': lambda x: x + 1})
  2. Out[190]:
  3. A B
  4. 2000-01-01 1.219234 -0.652700
  5. 2000-01-02 1.858653 0.261480
  6. 2000-01-03 0.112596 2.525897
  7. 2000-01-04 NaN NaN
  8. 2000-01-05 NaN NaN
  9. 2000-01-06 NaN NaN
  10. 2000-01-07 NaN NaN
  11. 2000-01-08 0.527790 -0.715506
  12. 2000-01-09 0.569341 1.569386
  13. 2000-01-10 0.413993 0.137720

Passing a dict of lists will generate a MultiIndexed DataFrame with these selective transforms.

  1. In [191]: tsdf.transform({'A': np.abs, 'B': [lambda x: x + 1, 'sqrt']})
  2. Out[191]:
  3. A B
  4. absolute <lambda> sqrt
  5. 2000-01-01 1.219234 -0.652700 NaN
  6. 2000-01-02 1.858653 0.261480 NaN
  7. 2000-01-03 0.112596 2.525897 1.235272
  8. 2000-01-04 NaN NaN NaN
  9. 2000-01-05 NaN NaN NaN
  10. 2000-01-06 NaN NaN NaN
  11. 2000-01-07 NaN NaN NaN
  12. 2000-01-08 0.527790 -0.715506 NaN
  13. 2000-01-09 0.569341 1.569386 0.754577
  14. 2000-01-10 0.413993 0.137720 NaN

Applying Elementwise 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:

  1. In [192]: df4
  2. Out[192]:
  3. one two three
  4. a 1.400810 -1.643041 NaN
  5. b -0.356470 1.045911 0.395023
  6. c 0.797268 0.924515 -0.007090
  7. d NaN 1.553693 -1.670830
  8. In [193]: def f(x):
  9. .....: return len(str(x))
  10. .....:
  11. In [194]: df4['one'].map(f)
  12. Out[194]:
  13. a 18
  14. b 19
  15. c 18
  16. d 3
  17. Name: one, dtype: int64
  18. In [195]: df4.applymap(f)
  19. Out[195]:
  20. one two three
  21. a 18 19 3
  22. b 19 18 19
  23. c 18 18 21
  24. d 3 18 19

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

  1. In [196]: s = pd.Series(['six', 'seven', 'six', 'seven', 'six'],
  2. .....: index=['a', 'b', 'c', 'd', 'e'])
  3. .....:
  4. In [197]: t = pd.Series({'six': 6., 'seven': 7.})
  5. In [198]: s
  6. Out[198]:
  7. a six
  8. b seven
  9. c six
  10. d seven
  11. e six
  12. dtype: object
  13. In [199]: s.map(t)
  14. Out[199]:
  15. a 6.0
  16. b 7.0
  17. c 6.0
  18. d 7.0
  19. e 6.0
  20. dtype: float64

Reindexing and altering labels

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

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

Here is a simple example:

  1. In [200]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
  2. In [201]: s
  3. Out[201]:
  4. a -0.368437
  5. b -0.036473
  6. c 0.774830
  7. d -0.310545
  8. e 0.709717
  9. dtype: float64
  10. In [202]: s.reindex(['e', 'b', 'f', 'd'])
  11. Out[202]:
  12. e 0.709717
  13. b -0.036473
  14. f NaN
  15. d -0.310545
  16. 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:

  1. In [203]: df
  2. Out[203]:
  3. one two three
  4. a 1.400810 -1.643041 NaN
  5. b -0.356470 1.045911 0.395023
  6. c 0.797268 0.924515 -0.007090
  7. d NaN 1.553693 -1.670830
  8. In [204]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
  9. Out[204]:
  10. three two one
  11. c -0.007090 0.924515 0.797268
  12. f NaN NaN NaN
  13. b 0.395023 1.045911 -0.356470

You may also use reindex with an axis keyword:

  1. In [205]: df.reindex(['c', 'f', 'b'], axis='index')
  2. Out[205]:
  3. one two three
  4. c 0.797268 0.924515 -0.007090
  5. f NaN NaN NaN
  6. b -0.356470 1.045911 0.395023

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:

  1. In [206]: rs = s.reindex(df.index)
  2. In [207]: rs
  3. Out[207]:
  4. a -0.368437
  5. b -0.036473
  6. c 0.774830
  7. d -0.310545
  8. dtype: float64
  9. In [208]: rs.index is df.index
  10. Out[208]: True

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

New in version 0.21.0.

DataFrame.reindex() also supports an “axis-style” calling convention, where you specify a single labels argument and the axis it applies to.

  1. In [209]: df.reindex(['c', 'f', 'b'], axis='index')
  2. Out[209]:
  3. one two three
  4. c 0.797268 0.924515 -0.007090
  5. f NaN NaN NaN
  6. b -0.356470 1.045911 0.395023
  7. In [210]: df.reindex(['three', 'two', 'one'], axis='columns')
  8. Out[210]:
  9. three two one
  10. a NaN -1.643041 1.400810
  11. b 0.395023 1.045911 -0.356470
  12. c -0.007090 0.924515 0.797268
  13. d -1.670830 1.553693 NaN

::: tip See also MultiIndex / Advanced Indexing is an even more concise way of doing reindexing. :::

::: tip 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:

  1. In [211]: df2
  2. Out[211]:
  3. one two
  4. a 1.400810 -1.643041
  5. b -0.356470 1.045911
  6. c 0.797268 0.924515
  7. In [212]: df3
  8. Out[212]:
  9. one two
  10. a 0.786941 -1.752170
  11. b -0.970339 0.936783
  12. c 0.183399 0.815387
  13. In [213]: df.reindex_like(df2)
  14. Out[213]:
  15. one two
  16. a 1.400810 -1.643041
  17. b -0.356470 1.045911
  18. c 0.797268 0.924515

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 (default)
  • 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:

  1. In [214]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
  2. In [215]: s1 = s[:4]
  3. In [216]: s2 = s[1:]
  4. In [217]: s1.align(s2)
  5. Out[217]:
  6. (a -0.610263
  7. b -0.170883
  8. c 0.367255
  9. d 0.273860
  10. e NaN
  11. dtype: float64, a NaN
  12. b -0.170883
  13. c 0.367255
  14. d 0.273860
  15. e 0.314782
  16. dtype: float64)
  17. In [218]: s1.align(s2, join='inner')
  18. Out[218]:
  19. (b -0.170883
  20. c 0.367255
  21. d 0.273860
  22. dtype: float64, b -0.170883
  23. c 0.367255
  24. d 0.273860
  25. dtype: float64)
  26. In [219]: s1.align(s2, join='left')
  27. Out[219]:
  28. (a -0.610263
  29. b -0.170883
  30. c 0.367255
  31. d 0.273860
  32. dtype: float64, a NaN
  33. b -0.170883
  34. c 0.367255
  35. d 0.273860
  36. dtype: float64)

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

  1. In [220]: df.align(df2, join='inner')
  2. Out[220]:
  3. ( one two
  4. a 1.400810 -1.643041
  5. b -0.356470 1.045911
  6. c 0.797268 0.924515, one two
  7. a 1.400810 -1.643041
  8. b -0.356470 1.045911
  9. c 0.797268 0.924515)

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

  1. In [221]: df.align(df2, join='inner', axis=0)
  2. Out[221]:
  3. ( one two three
  4. a 1.400810 -1.643041 NaN
  5. b -0.356470 1.045911 0.395023
  6. c 0.797268 0.924515 -0.007090, one two
  7. a 1.400810 -1.643041
  8. b -0.356470 1.045911
  9. c 0.797268 0.924515)

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:

  1. In [222]: df.align(df2.iloc[0], axis=1)
  2. Out[222]:
  3. ( one three two
  4. a 1.400810 NaN -1.643041
  5. b -0.356470 0.395023 1.045911
  6. c 0.797268 -0.007090 0.924515
  7. d NaN -1.670830 1.553693, one 1.400810
  8. three NaN
  9. two -1.643041
  10. 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
nearest Fill from the nearest index value

We illustrate these fill methods on a simple Series:

  1. In [223]: rng = pd.date_range('1/3/2000', periods=8)
  2. In [224]: ts = pd.Series(np.random.randn(8), index=rng)
  3. In [225]: ts2 = ts[[0, 3, 6]]
  4. In [226]: ts
  5. Out[226]:
  6. 2000-01-03 -0.082578
  7. 2000-01-04 0.768554
  8. 2000-01-05 0.398842
  9. 2000-01-06 -0.357956
  10. 2000-01-07 0.156403
  11. 2000-01-08 -1.347564
  12. 2000-01-09 0.253506
  13. 2000-01-10 1.228964
  14. Freq: D, dtype: float64
  15. In [227]: ts2
  16. Out[227]:
  17. 2000-01-03 -0.082578
  18. 2000-01-06 -0.357956
  19. 2000-01-09 0.253506
  20. dtype: float64
  21. In [228]: ts2.reindex(ts.index)
  22. Out[228]:
  23. 2000-01-03 -0.082578
  24. 2000-01-04 NaN
  25. 2000-01-05 NaN
  26. 2000-01-06 -0.357956
  27. 2000-01-07 NaN
  28. 2000-01-08 NaN
  29. 2000-01-09 0.253506
  30. 2000-01-10 NaN
  31. Freq: D, dtype: float64
  32. In [229]: ts2.reindex(ts.index, method='ffill')
  33. Out[229]:
  34. 2000-01-03 -0.082578
  35. 2000-01-04 -0.082578
  36. 2000-01-05 -0.082578
  37. 2000-01-06 -0.357956
  38. 2000-01-07 -0.357956
  39. 2000-01-08 -0.357956
  40. 2000-01-09 0.253506
  41. 2000-01-10 0.253506
  42. Freq: D, dtype: float64
  43. In [230]: ts2.reindex(ts.index, method='bfill')
  44. Out[230]:
  45. 2000-01-03 -0.082578
  46. 2000-01-04 -0.357956
  47. 2000-01-05 -0.357956
  48. 2000-01-06 -0.357956
  49. 2000-01-07 0.253506
  50. 2000-01-08 0.253506
  51. 2000-01-09 0.253506
  52. 2000-01-10 NaN
  53. Freq: D, dtype: float64
  54. In [231]: ts2.reindex(ts.index, method='nearest')
  55. Out[231]:
  56. 2000-01-03 -0.082578
  57. 2000-01-04 -0.082578
  58. 2000-01-05 -0.357956
  59. 2000-01-06 -0.357956
  60. 2000-01-07 -0.357956
  61. 2000-01-08 0.253506
  62. 2000-01-09 0.253506
  63. 2000-01-10 0.253506
  64. Freq: D, dtype: float64

These methods require that the indexes are ordered increasing or decreasing.

Note that the same result could have been achieved using fillna (except for method='nearest') or interpolate:

  1. In [232]: ts2.reindex(ts.index).fillna(method='ffill')
  2. Out[232]:
  3. 2000-01-03 -0.082578
  4. 2000-01-04 -0.082578
  5. 2000-01-05 -0.082578
  6. 2000-01-06 -0.357956
  7. 2000-01-07 -0.357956
  8. 2000-01-08 -0.357956
  9. 2000-01-09 0.253506
  10. 2000-01-10 0.253506
  11. Freq: D, dtype: float64

reindex() will raise a ValueError if the index is not monotonically increasing or decreasing. fillna() and interpolate() will not perform any checks on the order of the index.

Limits on filling while reindexing

The limit and tolerance arguments provide additional control over filling while reindexing. Limit specifies the maximum count of consecutive matches:

  1. In [233]: ts2.reindex(ts.index, method='ffill', limit=1)
  2. Out[233]:
  3. 2000-01-03 -0.082578
  4. 2000-01-04 -0.082578
  5. 2000-01-05 NaN
  6. 2000-01-06 -0.357956
  7. 2000-01-07 -0.357956
  8. 2000-01-08 NaN
  9. 2000-01-09 0.253506
  10. 2000-01-10 0.253506
  11. Freq: D, dtype: float64

In contrast, tolerance specifies the maximum distance between the index and indexer values:

  1. In [234]: ts2.reindex(ts.index, method='ffill', tolerance='1 day')
  2. Out[234]:
  3. 2000-01-03 -0.082578
  4. 2000-01-04 -0.082578
  5. 2000-01-05 NaN
  6. 2000-01-06 -0.357956
  7. 2000-01-07 -0.357956
  8. 2000-01-08 NaN
  9. 2000-01-09 0.253506
  10. 2000-01-10 0.253506
  11. Freq: D, dtype: float64

Notice that when used on a DatetimeIndex, TimedeltaIndex or PeriodIndex, tolerance will coerced into a Timedelta if possible. This allows you to specify tolerance with appropriate strings.

Dropping labels from an axis

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

  1. In [235]: df
  2. Out[235]:
  3. one two three
  4. a 1.400810 -1.643041 NaN
  5. b -0.356470 1.045911 0.395023
  6. c 0.797268 0.924515 -0.007090
  7. d NaN 1.553693 -1.670830
  8. In [236]: df.drop(['a', 'd'], axis=0)
  9. Out[236]:
  10. one two three
  11. b -0.356470 1.045911 0.395023
  12. c 0.797268 0.924515 -0.007090
  13. In [237]: df.drop(['one'], axis=1)
  14. Out[237]:
  15. two three
  16. a -1.643041 NaN
  17. b 1.045911 0.395023
  18. c 0.924515 -0.007090
  19. d 1.553693 -1.670830

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

  1. In [238]: df.reindex(df.index.difference(['a', 'd']))
  2. Out[238]:
  3. one two three
  4. b -0.356470 1.045911 0.395023
  5. c 0.797268 0.924515 -0.007090

Renaming / mapping labels

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

  1. In [239]: s
  2. Out[239]:
  3. a -0.610263
  4. b -0.170883
  5. c 0.367255
  6. d 0.273860
  7. e 0.314782
  8. dtype: float64
  9. In [240]: s.rename(str.upper)
  10. Out[240]:
  11. A -0.610263
  12. B -0.170883
  13. C 0.367255
  14. D 0.273860
  15. E 0.314782
  16. 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). A dict or Series can also be used:

  1. In [241]: df.rename(columns={'one': 'foo', 'two': 'bar'},
  2. .....: index={'a': 'apple', 'b': 'banana', 'd': 'durian'})
  3. .....:
  4. Out[241]:
  5. foo bar three
  6. apple 1.400810 -1.643041 NaN
  7. banana -0.356470 1.045911 0.395023
  8. c 0.797268 0.924515 -0.007090
  9. durian NaN 1.553693 -1.670830

If the mapping doesn’t include a column/index label, it isn’t renamed. Note that extra labels in the mapping don’t throw an error.

New in version 0.21.0.

DataFrame.rename() also supports an “axis-style” calling convention, where you specify a single mapper and the axis to apply that mapping to.

  1. In [242]: df.rename({'one': 'foo', 'two': 'bar'}, axis='columns')
  2. Out[242]:
  3. foo bar three
  4. a 1.400810 -1.643041 NaN
  5. b -0.356470 1.045911 0.395023
  6. c 0.797268 0.924515 -0.007090
  7. d NaN 1.553693 -1.670830
  8. In [243]: df.rename({'a': 'apple', 'b': 'banana', 'd': 'durian'}, axis='index')
  9. Out[243]:
  10. one two three
  11. apple 1.400810 -1.643041 NaN
  12. banana -0.356470 1.045911 0.395023
  13. c 0.797268 0.924515 -0.007090
  14. durian NaN 1.553693 -1.670830

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.

New in version 0.18.0.

Finally, rename() also accepts a scalar or list-like for altering the Series.name attribute.

  1. In [244]: s.rename("scalar-name")
  2. Out[244]:
  3. a -0.610263
  4. b -0.170883
  5. c 0.367255
  6. d 0.273860
  7. e 0.314782
  8. Name: scalar-name, dtype: float64

New in version 0.24.0.

The methods rename_axis() and rename_axis() allow specific names of a MultiIndex to be changed (as opposed to the labels).

  1. In [245]: df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6],
  2. .....: 'y': [10, 20, 30, 40, 50, 60]},
  3. .....: index=pd.MultiIndex.from_product([['a', 'b', 'c'], [1, 2]],
  4. .....: names=['let', 'num']))
  5. .....:
  6. In [246]: df
  7. Out[246]:
  8. x y
  9. let num
  10. a 1 1 10
  11. 2 2 20
  12. b 1 3 30
  13. 2 4 40
  14. c 1 5 50
  15. 2 6 60
  16. In [247]: df.rename_axis(index={'let': 'abc'})
  17. Out[247]:
  18. x y
  19. abc num
  20. a 1 1 10
  21. 2 2 20
  22. b 1 3 30
  23. 2 4 40
  24. c 1 5 50
  25. 2 6 60
  26. In [248]: df.rename_axis(index=str.upper)
  27. Out[248]:
  28. x y
  29. LET NUM
  30. a 1 1 10
  31. 2 2 20
  32. b 1 3 30
  33. 2 4 40
  34. c 1 5 50
  35. 2 6 60

Iteration

The behavior of basic iteration over pandas objects depends on the type. When iterating over a Series, it is regarded as array-like, and basic iteration produces the values. Other data structures, like DataFrame and Panel, follow the dict-like convention of iterating over the “keys” of the objects.

In short, basic iteration (for i in object) produces:

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

Thus, for example, iterating over a DataFrame gives you the column names:

  1. In [249]: df = pd.DataFrame({'col1': np.random.randn(3),
  2. .....: 'col2': np.random.randn(3)}, index=['a', 'b', 'c'])
  3. .....:
  4. In [250]: for col in df:
  5. .....: print(col)
  6. .....:
  7. col1
  8. col2

Pandas objects also have the dict-like iteritems() method to iterate over the (key, value) pairs.

To iterate over the rows of a DataFrame, you can use the following methods:

  • iterrows(): Iterate over the rows of a DataFrame as (index, Series) pairs. This converts the rows to Series objects, which can change the dtypes and has some performance implications.
  • itertuples(): Iterate over the rows of a DataFrame as namedtuples of the values. This is a lot faster than iterrows(), and is in most cases preferable to use to iterate over the values of a DataFrame.

::: Warning Warning Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided with one of the following approaches:

  • Look for a vectorized solution: many operations can be performed using built-in methods or NumPy functions, (boolean) indexing, …
  • When you have a function that cannot work on the full DataFrame/Series at once, it is better to use apply() instead of iterating over the values. See the docs on function application.
  • If you need to do iterative manipulations on the values but performance is important, consider writing the inner loop with cython or numba. See the enhancing performance section for some examples of this approach. :::

::: warning Warning Warning You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect!

For example, in the following case setting the value has no effect:

  1. In [251]: df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c']})
  2. In [252]: for index, row in df.iterrows():
  3. .....: row['a'] = 10
  4. .....:
  5. In [253]: df
  6. Out[253]:
  7. a b
  8. 0 1 a
  9. 1 2 b
  10. 2 3 c

:::

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:

  1. In [254]: for item, frame in wp.iteritems():
  2. .....: print(item)
  3. .....: print(frame)
  4. .....:
  5. Item1
  6. A B C D
  7. 2000-01-01 -1.157892 -1.344312 0.844885 1.075770
  8. 2000-01-02 -0.109050 1.643563 -1.469388 0.357021
  9. 2000-01-03 -0.674600 -1.776904 -0.968914 -1.294524
  10. 2000-01-04 0.413738 0.276662 -0.472035 -0.013960
  11. 2000-01-05 -0.362543 -0.006154 -0.923061 0.895717
  12. Item2
  13. A B C D
  14. 2000-01-01 0.805244 -1.206412 2.565646 1.431256
  15. 2000-01-02 1.340309 -1.170299 -0.226169 0.410835
  16. 2000-01-03 0.813850 0.132003 -0.827317 -0.076467
  17. 2000-01-04 -1.187678 1.130127 -1.436737 -1.413681
  18. 2000-01-05 1.607920 1.024180 0.569605 0.875906

iterrows

iterrows() allows you to iterate through the rows of a DataFrame as Series objects. It returns an iterator yielding each index value along with a Series containing the data in each row:

  1. In [255]: for row_index, row in df.iterrows():
  2. .....: print(row_index, row, sep='\n')
  3. .....:
  4. 0
  5. a 1
  6. b a
  7. Name: 0, dtype: object
  8. 1
  9. a 2
  10. b b
  11. Name: 1, dtype: object
  12. 2
  13. a 3
  14. b c
  15. Name: 2, dtype: object

::: tip Note Because iterrows() returns a Series for each row, it does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames). For example,

  1. In [256]: df_orig = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])
  2. In [257]: df_orig.dtypes
  3. Out[257]:
  4. int int64
  5. float float64
  6. dtype: object
  7. In [258]: row = next(df_orig.iterrows())[1]
  8. In [259]: row
  9. Out[259]:
  10. int 1.0
  11. float 1.5
  12. Name: 0, dtype: float64

All values in row, returned as a Series, are now upcasted to floats, also the original integer value in column x:

  1. In [260]: row['int'].dtype
  2. Out[260]: dtype('float64')
  3. In [261]: df_orig['int'].dtype
  4. Out[261]: dtype('int64')

To preserve dtypes while iterating over the rows, it is better to use itertuples() which returns namedtuples of the values and which is generally much faster than iterrows(). :::

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

  1. In [262]: df2 = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
  2. In [263]: print(df2)
  3. x y
  4. 0 1 4
  5. 1 2 5
  6. 2 3 6
  7. In [264]: print(df2.T)
  8. 0 1 2
  9. x 1 2 3
  10. y 4 5 6
  11. In [265]: df2_t = pd.DataFrame({idx: values for idx, values in df2.iterrows()})
  12. In [266]: print(df2_t)
  13. 0 1 2
  14. x 1 2 3
  15. y 4 5 6

itertuples

The itertuples() method will return an iterator yielding a namedtuple 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.

For instance:

  1. In [267]: for row in df.itertuples():
  2. .....: print(row)
  3. .....:
  4. Pandas(Index=0, a=1, b='a')
  5. Pandas(Index=1, a=2, b='b')
  6. Pandas(Index=2, a=3, b='c')

This method does not convert the row to a Series object; it merely returns the values inside a namedtuple. Therefore, itertuples() preserves the data type of the values and is generally faster as iterrows().

::: tip Note The column names will be renamed to positional names if they are invalid Python identifiers, repeated, or start with an underscore. With a large number of columns (>255), regular tuples are returned. :::

.dt accessor

Series has an accessor to succinctly return datetime like properties for the values of the Series, if it is a datetime/period like Series. This will return a Series, indexed like the existing Series.

  1. # datetime
  2. In [268]: s = pd.Series(pd.date_range('20130101 09:10:12', periods=4))
  3. In [269]: s
  4. Out[269]:
  5. 0 2013-01-01 09:10:12
  6. 1 2013-01-02 09:10:12
  7. 2 2013-01-03 09:10:12
  8. 3 2013-01-04 09:10:12
  9. dtype: datetime64[ns]
  10. In [270]: s.dt.hour
  11. Out[270]:
  12. 0 9
  13. 1 9
  14. 2 9
  15. 3 9
  16. dtype: int64
  17. In [271]: s.dt.second
  18. Out[271]:
  19. 0 12
  20. 1 12
  21. 2 12
  22. 3 12
  23. dtype: int64
  24. In [272]: s.dt.day
  25. Out[272]:
  26. 0 1
  27. 1 2
  28. 2 3
  29. 3 4
  30. dtype: int64

This enables nice expressions like this:

  1. In [273]: s[s.dt.day == 2]
  2. Out[273]:
  3. 1 2013-01-02 09:10:12
  4. dtype: datetime64[ns]

You can easily produces tz aware transformations:

  1. In [274]: stz = s.dt.tz_localize('US/Eastern')
  2. In [275]: stz
  3. Out[275]:
  4. 0 2013-01-01 09:10:12-05:00
  5. 1 2013-01-02 09:10:12-05:00
  6. 2 2013-01-03 09:10:12-05:00
  7. 3 2013-01-04 09:10:12-05:00
  8. dtype: datetime64[ns, US/Eastern]
  9. In [276]: stz.dt.tz
  10. Out[276]: <DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>

You can also chain these types of operations:

  1. In [277]: s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
  2. Out[277]:
  3. 0 2013-01-01 04:10:12-05:00
  4. 1 2013-01-02 04:10:12-05:00
  5. 2 2013-01-03 04:10:12-05:00
  6. 3 2013-01-04 04:10:12-05:00
  7. dtype: datetime64[ns, US/Eastern]

You can also format datetime values as strings with Series.dt.strftime() which supports the same format as the standard strftime().

  1. # DatetimeIndex
  2. In [278]: s = pd.Series(pd.date_range('20130101', periods=4))
  3. In [279]: s
  4. Out[279]:
  5. 0 2013-01-01
  6. 1 2013-01-02
  7. 2 2013-01-03
  8. 3 2013-01-04
  9. dtype: datetime64[ns]
  10. In [280]: s.dt.strftime('%Y/%m/%d')
  11. Out[280]:
  12. 0 2013/01/01
  13. 1 2013/01/02
  14. 2 2013/01/03
  15. 3 2013/01/04
  16. dtype: object
  1. # PeriodIndex
  2. In [281]: s = pd.Series(pd.period_range('20130101', periods=4))
  3. In [282]: s
  4. Out[282]:
  5. 0 2013-01-01
  6. 1 2013-01-02
  7. 2 2013-01-03
  8. 3 2013-01-04
  9. dtype: period[D]
  10. In [283]: s.dt.strftime('%Y/%m/%d')
  11. Out[283]:
  12. 0 2013/01/01
  13. 1 2013/01/02
  14. 2 2013/01/03
  15. 3 2013/01/04
  16. dtype: object

The .dt accessor works for period and timedelta dtypes.

  1. # period
  2. In [284]: s = pd.Series(pd.period_range('20130101', periods=4, freq='D'))
  3. In [285]: s
  4. Out[285]:
  5. 0 2013-01-01
  6. 1 2013-01-02
  7. 2 2013-01-03
  8. 3 2013-01-04
  9. dtype: period[D]
  10. In [286]: s.dt.year
  11. Out[286]:
  12. 0 2013
  13. 1 2013
  14. 2 2013
  15. 3 2013
  16. dtype: int64
  17. In [287]: s.dt.day
  18. Out[287]:
  19. 0 1
  20. 1 2
  21. 2 3
  22. 3 4
  23. dtype: int64
  1. # timedelta
  2. In [288]: s = pd.Series(pd.timedelta_range('1 day 00:00:05', periods=4, freq='s'))
  3. In [289]: s
  4. Out[289]:
  5. 0 1 days 00:00:05
  6. 1 1 days 00:00:06
  7. 2 1 days 00:00:07
  8. 3 1 days 00:00:08
  9. dtype: timedelta64[ns]
  10. In [290]: s.dt.days
  11. Out[290]:
  12. 0 1
  13. 1 1
  14. 2 1
  15. 3 1
  16. dtype: int64
  17. In [291]: s.dt.seconds
  18. Out[291]:
  19. 0 5
  20. 1 6
  21. 2 7
  22. 3 8
  23. dtype: int64
  24. In [292]: s.dt.components
  25. Out[292]:
  26. days hours minutes seconds milliseconds microseconds nanoseconds
  27. 0 1 0 0 5 0 0 0
  28. 1 1 0 0 6 0 0 0
  29. 2 1 0 0 7 0 0 0
  30. 3 1 0 0 8 0 0 0

::: tip Note Series.dt will raise a TypeError if you access with a non-datetime-like values. :::

Vectorized string methods

Series is equipped 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) built-in string methods. For example:

  1. In [293]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
  2. In [294]: s.str.lower()
  3. Out[294]:
  4. 0 a
  5. 1 b
  6. 2 c
  7. 3 aaba
  8. 4 baca
  9. 5 NaN
  10. 6 caba
  11. 7 dog
  12. 8 cat
  13. dtype: object

Powerful pattern-matching methods are provided as well, but note that pattern-matching generally uses regular expressions by default (and in some cases always uses them).

Please see Vectorized String Methods for a complete description.

Sorting

Pandas supports three kinds of sorting: sorting by index labels, sorting by column values, and sorting by a combination of both.

By Index

The Series.sort_index() and DataFrame.sort_index() methods are used to sort a pandas object by its index levels.

  1. In [295]: df = pd.DataFrame({
  2. .....: 'one': pd.Series(np.random.randn(3), index=['a', 'b', 'c']),
  3. .....: 'two': pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),
  4. .....: 'three': pd.Series(np.random.randn(3), index=['b', 'c', 'd'])})
  5. .....:
  6. In [296]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
  7. .....: columns=['three', 'two', 'one'])
  8. .....:
  9. In [297]: unsorted_df
  10. Out[297]:
  11. three two one
  12. a NaN -0.867293 0.050162
  13. d 1.215473 -0.051744 NaN
  14. c -0.421091 -0.712097 0.953102
  15. b 1.205223 0.632624 -1.534113
  16. # DataFrame
  17. In [298]: unsorted_df.sort_index()
  18. Out[298]:
  19. three two one
  20. a NaN -0.867293 0.050162
  21. b 1.205223 0.632624 -1.534113
  22. c -0.421091 -0.712097 0.953102
  23. d 1.215473 -0.051744 NaN
  24. In [299]: unsorted_df.sort_index(ascending=False)
  25. Out[299]:
  26. three two one
  27. d 1.215473 -0.051744 NaN
  28. c -0.421091 -0.712097 0.953102
  29. b 1.205223 0.632624 -1.534113
  30. a NaN -0.867293 0.050162
  31. In [300]: unsorted_df.sort_index(axis=1)
  32. Out[300]:
  33. one three two
  34. a 0.050162 NaN -0.867293
  35. d NaN 1.215473 -0.051744
  36. c 0.953102 -0.421091 -0.712097
  37. b -1.534113 1.205223 0.632624
  38. # Series
  39. In [301]: unsorted_df['three'].sort_index()
  40. Out[301]:
  41. a NaN
  42. b 1.205223
  43. c -0.421091
  44. d 1.215473
  45. Name: three, dtype: float64

By Values

The Series.sort_values() method is used to sort a Series by its values. The DataFrame.sort_values() method is used to sort a DataFrame by its column or row values. The optional by parameter to DataFrame.sort_values() may used to specify one or more columns to use to determine the sorted order.

  1. In [302]: df1 = pd.DataFrame({'one': [2, 1, 1, 1],
  2. .....: 'two': [1, 3, 2, 4],
  3. .....: 'three': [5, 4, 3, 2]})
  4. .....:
  5. In [303]: df1.sort_values(by='two')
  6. Out[303]:
  7. one two three
  8. 0 2 1 5
  9. 2 1 2 3
  10. 1 1 3 4
  11. 3 1 4 2

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

  1. In [304]: df1[['one', 'two', 'three']].sort_values(by=['one', 'two'])
  2. Out[304]:
  3. one two three
  4. 2 1 2 3
  5. 1 1 3 4
  6. 3 1 4 2
  7. 0 2 1 5

These methods have special treatment of NA values via the na_position argument:

  1. In [305]: s[2] = np.nan
  2. In [306]: s.sort_values()
  3. Out[306]:
  4. 0 A
  5. 3 Aaba
  6. 1 B
  7. 4 Baca
  8. 6 CABA
  9. 8 cat
  10. 7 dog
  11. 2 NaN
  12. 5 NaN
  13. dtype: object
  14. In [307]: s.sort_values(na_position='first')
  15. Out[307]:
  16. 2 NaN
  17. 5 NaN
  18. 0 A
  19. 3 Aaba
  20. 1 B
  21. 4 Baca
  22. 6 CABA
  23. 8 cat
  24. 7 dog
  25. dtype: object

By Indexes and Values

New in version 0.23.0.

Strings passed as the by parameter to DataFrame.sort_values() may refer to either columns or index level names.

  1. # Build MultiIndex
  2. In [308]: idx = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('a', 2),
  3. .....: ('b', 2), ('b', 1), ('b', 1)])
  4. .....:
  5. In [309]: idx.names = ['first', 'second']
  6. # Build DataFrame
  7. In [310]: df_multi = pd.DataFrame({'A': np.arange(6, 0, -1)},
  8. .....: index=idx)
  9. .....:
  10. In [311]: df_multi
  11. Out[311]:
  12. A
  13. first second
  14. a 1 6
  15. 2 5
  16. 2 4
  17. b 2 3
  18. 1 2
  19. 1 1

Sort by ‘second’ (index) and ‘A’ (column)

  1. In [312]: df_multi.sort_values(by=['second', 'A'])
  2. Out[312]:
  3. A
  4. first second
  5. b 1 1
  6. 1 2
  7. a 1 6
  8. b 2 3
  9. a 2 4
  10. 2 5

::: tip Note Note If a string matches both a column name and an index level name then a warning is issued and the column takes precedence. This will result in an ambiguity error in a future version. :::

searchsorted

Series has the searchsorted() method, which works similarly to numpy.ndarray.searchsorted().

  1. In [313]: ser = pd.Series([1, 2, 3])
  2. In [314]: ser.searchsorted([0, 3])
  3. Out[314]: array([0, 2])
  4. In [315]: ser.searchsorted([0, 4])
  5. Out[315]: array([0, 3])
  6. In [316]: ser.searchsorted([1, 3], side='right')
  7. Out[316]: array([1, 3])
  8. In [317]: ser.searchsorted([1, 3], side='left')
  9. Out[317]: array([0, 2])
  10. In [318]: ser = pd.Series([3, 1, 2])
  11. In [319]: ser.searchsorted([0, 3], sorter=np.argsort(ser))
  12. Out[319]: array([0, 2])

smallest / largest values

Series has the nsmallest() and nlargest() methods which return the smallest or largest 𝑛 values. For a large Series this can be much faster than sorting the entire Series and calling head(n) on the result.

  1. In [320]: s = pd.Series(np.random.permutation(10))
  2. In [321]: s
  3. Out[321]:
  4. 0 5
  5. 1 3
  6. 2 2
  7. 3 0
  8. 4 7
  9. 5 6
  10. 6 9
  11. 7 1
  12. 8 4
  13. 9 8
  14. dtype: int64
  15. In [322]: s.sort_values()
  16. Out[322]:
  17. 3 0
  18. 7 1
  19. 2 2
  20. 1 3
  21. 8 4
  22. 0 5
  23. 5 6
  24. 4 7
  25. 9 8
  26. 6 9
  27. dtype: int64
  28. In [323]: s.nsmallest(3)
  29. Out[323]:
  30. 3 0
  31. 7 1
  32. 2 2
  33. dtype: int64
  34. In [324]: s.nlargest(3)
  35. Out[324]:
  36. 6 9
  37. 9 8
  38. 4 7
  39. dtype: int64

DataFrame also has the nlargest and nsmallest methods.

  1. In [325]: df = pd.DataFrame({'a': [-2, -1, 1, 10, 8, 11, -1],
  2. .....: 'b': list('abdceff'),
  3. .....: 'c': [1.0, 2.0, 4.0, 3.2, np.nan, 3.0, 4.0]})
  4. .....:
  5. In [326]: df.nlargest(3, 'a')
  6. Out[326]:
  7. a b c
  8. 5 11 f 3.0
  9. 3 10 c 3.2
  10. 4 8 e NaN
  11. In [327]: df.nlargest(5, ['a', 'c'])
  12. Out[327]:
  13. a b c
  14. 5 11 f 3.0
  15. 3 10 c 3.2
  16. 4 8 e NaN
  17. 2 1 d 4.0
  18. 6 -1 f 4.0
  19. In [328]: df.nsmallest(3, 'a')
  20. Out[328]:
  21. a b c
  22. 0 -2 a 1.0
  23. 1 -1 b 2.0
  24. 6 -1 f 4.0
  25. In [329]: df.nsmallest(5, ['a', 'c'])
  26. Out[329]:
  27. a b c
  28. 0 -2 a 1.0
  29. 1 -1 b 2.0
  30. 6 -1 f 4.0
  31. 2 1 d 4.0
  32. 4 8 e NaN

Sorting by a MultiIndex column

You must be explicit about sorting when the column is a MultiIndex, and fully specify all levels to by.

  1. In [330]: df1.columns = pd.MultiIndex.from_tuples([('a', 'one'),
  2. .....: ('a', 'two'),
  3. .....: ('b', 'three')])
  4. .....:
  5. In [331]: df1.sort_values(by=('a', 'two'))
  6. Out[331]:
  7. a b
  8. one two three
  9. 0 2 1 5
  10. 2 1 2 3
  11. 1 1 3 4
  12. 3 1 4 2

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 method has the side effect of modifying your data; almost every method returns a new object, leaving the original object untouched. If the data is modified, it is because you did so explicitly.

dtypes

For the most part, pandas uses NumPy arrays and dtypes for Series or individual columns of a DataFrame. NumPy provides support for float, int, bool, timedelta64[ns] and datetime64[ns] (note that NumPy does not support timezone-aware datetimes).

Pandas and third-party libraries extend NumPy’s type system in a few places. This section describes the extensions pandas has made internally. See Extension Types for how to write your own extension that works with pandas. See Extension Data Types for a list of third-party libraries that have implemented an extension.

The following table lists all of pandas extension types. See the respective documentation sections for more on each type.

Kind of Data Data Type Scalar Array Documentation
tz-aware datetime DatetimeTZDtype Timestamp arrays.DatetimeArray Time Zone Handling
Categorical CategoricalDtype (none) Categorical Categorical Data
period (time spans) PeriodDtype Period arrays.PeriodArray Time Span Representation
sparse SparseDtype (none) arrays.SparseArray Sparse data structures
intervals IntervalDtype Interval arrays.IntervalArray IntervalIndex
nullable integer Int64Dtype, … (none) arrays.IntegerArray Nullable Integer Data Type

Pandas uses the object dtype for storing strings.

Finally, arbitrary objects may be stored using the object dtype, but should be avoided to the extent possible (for performance and interoperability with other libraries and methods. See object conversion).

A convenient dtypes attribute for DataFrame returns a Series with the data type of each column.

  1. In [332]: dft = pd.DataFrame({'A': np.random.rand(3),
  2. .....: 'B': 1,
  3. .....: 'C': 'foo',
  4. .....: 'D': pd.Timestamp('20010102'),
  5. .....: 'E': pd.Series([1.0] * 3).astype('float32'),
  6. .....: 'F': False,
  7. .....: 'G': pd.Series([1] * 3, dtype='int8')})
  8. .....:
  9. In [333]: dft
  10. Out[333]:
  11. A B C D E F G
  12. 0 0.278831 1 foo 2001-01-02 1.0 False 1
  13. 1 0.242124 1 foo 2001-01-02 1.0 False 1
  14. 2 0.078031 1 foo 2001-01-02 1.0 False 1
  15. In [334]: dft.dtypes
  16. Out[334]:
  17. A float64
  18. B int64
  19. C object
  20. D datetime64[ns]
  21. E float32
  22. F bool
  23. G int8
  24. dtype: object

On a Series object, use the dtype attribute.

  1. In [335]: dft['A'].dtype
  2. Out[335]: dtype('float64')

If a pandas object contains data with 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).

  1. # these ints are coerced to floats
  2. In [336]: pd.Series([1, 2, 3, 4, 5, 6.])
  3. Out[336]:
  4. 0 1.0
  5. 1 2.0
  6. 2 3.0
  7. 3 4.0
  8. 4 5.0
  9. 5 6.0
  10. dtype: float64
  11. # string data forces an ``object`` dtype
  12. In [337]: pd.Series([1, 2, 3, 6., 'foo'])
  13. Out[337]:
  14. 0 1
  15. 1 2
  16. 2 3
  17. 3 6
  18. 4 foo
  19. dtype: object

The number of columns of each type in a DataFrame can be found by calling get_dtype_counts().

  1. In [338]: dft.get_dtype_counts()
  2. Out[338]:
  3. float64 1
  4. float32 1
  5. int64 1
  6. int8 1
  7. datetime64[ns] 1
  8. bool 1
  9. object 1
  10. dtype: int64

Numeric dtypes will propagate and can coexist in DataFrames. 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.

  1. Frame(np.random.randn(8, 1), columns=['A'], dtype='float32')
  2. In [340]: df1
  3. Out[340]:
  4. A
  5. 0 -1.641339
  6. 1 -0.314062
  7. 2 -0.679206
  8. 3 1.178243
  9. 4 0.181790
  10. 5 -2.044248
  11. 6 1.151282
  12. 7 -1.641398
  13. In [341]: df1.dtypes
  14. Out[341]:
  15. A float32
  16. dtype: object
  17. In [342]: df2 = pd.DataFrame({'A': pd.Series(np.random.randn(8), dtype='float16'),
  18. .....: 'B': pd.Series(np.random.randn(8)),
  19. .....: 'C': pd.Series(np.array(np.random.randn(8),
  20. .....: dtype='uint8'))})
  21. .....:
  22. In [343]: df2
  23. Out[343]:
  24. A B C
  25. 0 0.130737 -1.143729 1
  26. 1 0.289551 2.787500 0
  27. 2 0.590820 -0.708143 254
  28. 3 -0.020142 -1.512388 0
  29. 4 -1.048828 -0.243145 1
  30. 5 -0.808105 -0.650992 0
  31. 6 1.373047 2.090108 0
  32. 7 -0.254395 0.433098 0
  33. In [344]: df2.dtypes
  34. Out[344]:
  35. A float16
  36. B float64
  37. C uint8
  38. 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.

  1. In [345]: pd.DataFrame([1, 2], columns=['a']).dtypes
  2. Out[345]:
  3. a int64
  4. dtype: object
  5. In [346]: pd.DataFrame({'a': [1, 2]}).dtypes
  6. Out[346]:
  7. a int64
  8. dtype: object
  9. In [347]: pd.DataFrame({'a': 1}, index=list(range(2))).dtypes
  10. Out[347]:
  11. a int64
  12. dtype: object

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

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

upcasting

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

  1. In [349]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2
  2. In [350]: df3
  3. Out[350]:
  4. A B C
  5. 0 -1.510602 -1.143729 1.0
  6. 1 -0.024511 2.787500 0.0
  7. 2 -0.088385 -0.708143 254.0
  8. 3 1.158101 -1.512388 0.0
  9. 4 -0.867039 -0.243145 1.0
  10. 5 -2.852354 -0.650992 0.0
  11. 6 2.524329 2.090108 0.0
  12. 7 -1.895793 0.433098 0.0
  13. In [351]: df3.dtypes
  14. Out[351]:
  15. A float32
  16. B float64
  17. C float64
  18. dtype: object

DataFrame.to_numpy() will return the lower-common-denominator of the dtypes, meaning the dtype that can accommodate ALL of the types in the resulting homogeneous dtyped NumPy array. This can force some upcasting.

  1. In [352]: df3.to_numpy().dtype
  2. Out[352]: 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.

  1. In [353]: df3
  2. Out[353]:
  3. A B C
  4. 0 -1.510602 -1.143729 1.0
  5. 1 -0.024511 2.787500 0.0
  6. 2 -0.088385 -0.708143 254.0
  7. 3 1.158101 -1.512388 0.0
  8. 4 -0.867039 -0.243145 1.0
  9. 5 -2.852354 -0.650992 0.0
  10. 6 2.524329 2.090108 0.0
  11. 7 -1.895793 0.433098 0.0
  12. In [354]: df3.dtypes
  13. Out[354]:
  14. A float32
  15. B float64
  16. C float64
  17. dtype: object
  18. # conversion of dtypes
  19. In [355]: df3.astype('float32').dtypes
  20. Out[355]:
  21. A float32
  22. B float32
  23. C float32
  24. dtype: object

Convert a subset of columns to a specified type using astype().

  1. In [356]: dft = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
  2. In [357]: dft[['a', 'b']] = dft[['a', 'b']].astype(np.uint8)
  3. In [358]: dft
  4. Out[358]:
  5. a b c
  6. 0 1 4 7
  7. 1 2 5 8
  8. 2 3 6 9
  9. In [359]: dft.dtypes
  10. Out[359]:
  11. a uint8
  12. b uint8
  13. c int64
  14. dtype: object

New in version 0.19.0.

Convert certain columns to a specific dtype by passing a dict to astype().

  1. In [360]: dft1 = pd.DataFrame({'a': [1, 0, 1], 'b': [4, 5, 6], 'c': [7, 8, 9]})
  2. In [361]: dft1 = dft1.astype({'a': np.bool, 'c': np.float64})
  3. In [362]: dft1
  4. Out[362]:
  5. a b c
  6. 0 True 4 7.0
  7. 1 False 5 8.0
  8. 2 True 6 9.0
  9. In [363]: dft1.dtypes
  10. Out[363]:
  11. a bool
  12. b int64
  13. c float64
  14. dtype: object

::: tip Note

When trying to convert a subset of columns to a specified type using astype() and loc(), upcasting occurs.

loc() tries to fit in what we are assigning to the current dtypes, while [] will overwrite them taking the dtype from the right hand side. Therefore the following piece of code produces the unintended result.

  1. In [364]: dft = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
  2. In [365]: dft.loc[:, ['a', 'b']].astype(np.uint8).dtypes
  3. Out[365]:
  4. a uint8
  5. b uint8
  6. dtype: object
  7. In [366]: dft.loc[:, ['a', 'b']] = dft.loc[:, ['a', 'b']].astype(np.uint8)
  8. In [367]: dft.dtypes
  9. Out[367]:
  10. a int64
  11. b int64
  12. c int64
  13. dtype: object

:::

object conversion

pandas offers various functions to try to force conversion of types from the object dtype to other types. In cases where the data is already of the correct type, but stored in an object array, the DataFrame.infer_objects() and Series.infer_objects() methods can be used to soft convert to the correct type.

  1. In [368]: import datetime
  2. In [369]: df = pd.DataFrame([[1, 2],
  3. .....: ['a', 'b'],
  4. .....: [datetime.datetime(2016, 3, 2),
  5. .....: datetime.datetime(2016, 3, 2)]])
  6. .....:
  7. In [370]: df = df.T
  8. In [371]: df
  9. Out[371]:
  10. 0 1 2
  11. 0 1 a 2016-03-02 00:00:00
  12. 1 2 b 2016-03-02 00:00:00
  13. In [372]: df.dtypes
  14. Out[372]:
  15. 0 object
  16. 1 object
  17. 2 object
  18. dtype: object

Because the data was transposed the original inference stored all columns as object, which infer_objects will correct.

  1. In [373]: df.infer_objects().dtypes
  2. Out[373]:
  3. 0 int64
  4. 1 object
  5. 2 datetime64[ns]
  6. dtype: object

The following functions are available for one dimensional object arrays or scalars to perform hard conversion of objects to a specified type:

  • to_numeric() (conversion to numeric dtypes)

    1. In [374]: m = ['1.1', 2, 3]
    2. In [375]: pd.to_numeric(m)
    3. Out[375]: array([ 1.1, 2. , 3. ])
  • to_datetime() (conversion to datetime objects)

    1. In [376]: import datetime
    2. In [377]: m = ['2016-07-09', datetime.datetime(2016, 3, 2)]
    3. In [378]: pd.to_datetime(m)
    4. Out[378]: DatetimeIndex(['2016-07-09', '2016-03-02'], dtype='datetime64[ns]', freq=None)
  • to_timedelta() (conversion to timedelta objects)

    1. In [379]: m = ['5us', pd.Timedelta('1day')]
    2. In [380]: pd.to_timedelta(m)
    3. Out[380]: TimedeltaIndex(['0 days 00:00:00.000005', '1 days 00:00:00'], dtype='timedelta64[ns]', freq=None)

To force a conversion, we can pass in an errors argument, which specifies how pandas should deal with elements that cannot be converted to desired dtype or object. By default, errors='raise', meaning that any errors encountered will be raised during the conversion process. However, if errors='coerce', these errors will be ignored and pandas will convert problematic elements to pd.NaT (for datetime and timedelta) or np.nan (for numeric). This might be useful if you are reading in data which is mostly of the desired dtype (e.g. numeric, datetime), but occasionally has non-conforming elements intermixed that you want to represent as missing:

  1. In [381]: import datetime
  2. In [382]: m = ['apple', datetime.datetime(2016, 3, 2)]
  3. In [383]: pd.to_datetime(m, errors='coerce')
  4. Out[383]: DatetimeIndex(['NaT', '2016-03-02'], dtype='datetime64[ns]', freq=None)
  5. In [384]: m = ['apple', 2, 3]
  6. In [385]: pd.to_numeric(m, errors='coerce')
  7. Out[385]: array([ nan, 2., 3.])
  8. In [386]: m = ['apple', pd.Timedelta('1day')]
  9. In [387]: pd.to_timedelta(m, errors='coerce')
  10. Out[387]: TimedeltaIndex([NaT, '1 days'], dtype='timedelta64[ns]', freq=None)

The errors parameter has a third option of errors='ignore', which will simply return the passed in data if it encounters any errors with the conversion to a desired data type:

  1. In [388]: import datetime
  2. In [389]: m = ['apple', datetime.datetime(2016, 3, 2)]
  3. In [390]: pd.to_datetime(m, errors='ignore')
  4. Out[390]: Index(['apple', 2016-03-02 00:00:00], dtype='object')
  5. In [391]: m = ['apple', 2, 3]
  6. In [392]: pd.to_numeric(m, errors='ignore')
  7. Out[392]: array(['apple', 2, 3], dtype=object)
  8. In [393]: m = ['apple', pd.Timedelta('1day')]
  9. In [394]: pd.to_timedelta(m, errors='ignore')
  10. Out[394]: array(['apple', Timedelta('1 days 00:00:00')], dtype=object)

In addition to object conversion, to_numeric() provides another argument downcast, which gives the option of downcasting the newly (or already) numeric data to a smaller dtype, which can conserve memory:

  1. In [395]: m = ['1', 2, 3]
  2. In [396]: pd.to_numeric(m, downcast='integer') # smallest signed int dtype
  3. Out[396]: array([1, 2, 3], dtype=int8)
  4. In [397]: pd.to_numeric(m, downcast='signed') # same as 'integer'
  5. Out[397]: array([1, 2, 3], dtype=int8)
  6. In [398]: pd.to_numeric(m, downcast='unsigned') # smallest unsigned int dtype
  7. Out[398]: array([1, 2, 3], dtype=uint8)
  8. In [399]: pd.to_numeric(m, downcast='float') # smallest float dtype
  9. Out[399]: array([ 1., 2., 3.], dtype=float32)

As these methods apply only to one-dimensional arrays, lists or scalars; they cannot be used directly on multi-dimensional objects such as DataFrames. However, with apply(), we can “apply” the function over each column efficiently:

  1. In [400]: import datetime
  2. In [401]: df = pd.DataFrame([
  3. .....: ['2016-07-09', datetime.datetime(2016, 3, 2)]] * 2, dtype='O')
  4. .....:
  5. In [402]: df
  6. Out[402]:
  7. 0 1
  8. 0 2016-07-09 2016-03-02 00:00:00
  9. 1 2016-07-09 2016-03-02 00:00:00
  10. In [403]: df.apply(pd.to_datetime)
  11. Out[403]:
  12. 0 1
  13. 0 2016-07-09 2016-03-02
  14. 1 2016-07-09 2016-03-02
  15. In [404]: df = pd.DataFrame([['1.1', 2, 3]] * 2, dtype='O')
  16. In [405]: df
  17. Out[405]:
  18. 0 1 2
  19. 0 1.1 2 3
  20. 1 1.1 2 3
  21. In [406]: df.apply(pd.to_numeric)
  22. Out[406]:
  23. 0 1 2
  24. 0 1.1 2 3
  25. 1 1.1 2 3
  26. In [407]: df = pd.DataFrame([['5us', pd.Timedelta('1day')]] * 2, dtype='O')
  27. In [408]: df
  28. Out[408]:
  29. 0 1
  30. 0 5us 1 days 00:00:00
  31. 1 5us 1 days 00:00:00
  32. In [409]: df.apply(pd.to_timedelta)
  33. Out[409]:
  34. 0 1
  35. 0 00:00:00.000005 1 days
  36. 1 00:00:00.000005 1 days

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. See also Support for integer NA.

  1. In [410]: dfi = df3.astype('int32')
  2. In [411]: dfi['E'] = 1
  3. In [412]: dfi
  4. Out[412]:
  5. A B C E
  6. 0 -1 -1 1 1
  7. 1 0 2 0 1
  8. 2 0 0 254 1
  9. 3 1 -1 0 1
  10. 4 0 0 1 1
  11. 5 -2 0 0 1
  12. 6 2 2 0 1
  13. 7 -1 0 0 1
  14. In [413]: dfi.dtypes
  15. Out[413]:
  16. A int32
  17. B int32
  18. C int32
  19. E int64
  20. dtype: object
  21. In [414]: casted = dfi[dfi > 0]
  22. In [415]: casted
  23. Out[415]:
  24. A B C E
  25. 0 NaN NaN 1.0 1
  26. 1 NaN 2.0 NaN 1
  27. 2 NaN NaN 254.0 1
  28. 3 1.0 NaN NaN 1
  29. 4 NaN NaN 1.0 1
  30. 5 NaN NaN NaN 1
  31. 6 2.0 2.0 NaN 1
  32. 7 NaN NaN NaN 1
  33. In [416]: casted.dtypes
  34. Out[416]:
  35. A float64
  36. B float64
  37. C float64
  38. E int64
  39. dtype: object

While float dtypes are unchanged.

  1. In [417]: dfa = df3.copy()
  2. In [418]: dfa['A'] = dfa['A'].astype('float32')
  3. In [419]: dfa.dtypes
  4. Out[419]:
  5. A float32
  6. B float64
  7. C float64
  8. dtype: object
  9. In [420]: casted = dfa[df2 > 0]
  10. In [421]: casted
  11. Out[421]:
  12. A B C
  13. 0 -1.510602 NaN 1.0
  14. 1 -0.024511 2.787500 NaN
  15. 2 -0.088385 NaN 254.0
  16. 3 NaN NaN NaN
  17. 4 NaN NaN 1.0
  18. 5 NaN NaN NaN
  19. 6 2.524329 2.090108 NaN
  20. 7 NaN 0.433098 NaN
  21. In [422]: casted.dtypes
  22. Out[422]:
  23. A float32
  24. B float64
  25. C float64
  26. dtype: object

Selecting columns based on dtype

The select_dtypes() method implements subsetting of columns based on their dtype.

First, let’s create a DataFrame with a slew of different dtypes:

  1. In [423]: df = pd.DataFrame({'string': list('abc'),
  2. .....: 'int64': list(range(1, 4)),
  3. .....: 'uint8': np.arange(3, 6).astype('u1'),
  4. .....: 'float64': np.arange(4.0, 7.0),
  5. .....: 'bool1': [True, False, True],
  6. .....: 'bool2': [False, True, False],
  7. .....: 'dates': pd.date_range('now', periods=3),
  8. .....: 'category': pd.Series(list("ABC")).astype('category')})
  9. .....:
  10. In [424]: df['tdeltas'] = df.dates.diff()
  11. In [425]: df['uint64'] = np.arange(3, 6).astype('u8')
  12. In [426]: df['other_dates'] = pd.date_range('20130101', periods=3)
  13. In [427]: df['tz_aware_dates'] = pd.date_range('20130101', periods=3, tz='US/Eastern')
  14. In [428]: df
  15. Out[428]:
  16. string int64 uint8 float64 bool1 bool2 dates category tdeltas uint64 other_dates tz_aware_dates
  17. 0 a 1 3 4.0 True False 2019-03-12 22:38:38.692567 A NaT 3 2013-01-01 2013-01-01 00:00:00-05:00
  18. 1 b 2 4 5.0 False True 2019-03-13 22:38:38.692567 B 1 days 4 2013-01-02 2013-01-02 00:00:00-05:00
  19. 2 c 3 5 6.0 True False 2019-03-14 22:38:38.692567 C 1 days 5 2013-01-03 2013-01-03 00:00:00-05:00

And the dtypes:

  1. In [429]: df.dtypes
  2. Out[429]:
  3. string object
  4. int64 int64
  5. uint8 uint8
  6. float64 float64
  7. bool1 bool
  8. bool2 bool
  9. dates datetime64[ns]
  10. category category
  11. tdeltas timedelta64[ns]
  12. uint64 uint64
  13. other_dates datetime64[ns]
  14. tz_aware_dates datetime64[ns, US/Eastern]
  15. dtype: object

select_dtypes() has two parameters include and exclude that allow you to say “give me the columns with these dtypes” (include) and/or “give the columns without these dtypes” (exclude).

For example, to select bool columns:

  1. In [430]: df.select_dtypes(include=[bool])
  2. Out[430]:
  3. bool1 bool2
  4. 0 True False
  5. 1 False True
  6. 2 True False

You can also pass the name of a dtype in the NumPy dtype hierarchy:

  1. In [431]: df.select_dtypes(include=['bool'])
  2. Out[431]:
  3. bool1 bool2
  4. 0 True False
  5. 1 False True
  6. 2 True False

select_dtypes() also works with generic dtypes as well.

For example, to select all numeric and boolean columns while excluding unsigned integers:

  1. In [432]: df.select_dtypes(include=['number', 'bool'], exclude=['unsignedinteger'])
  2. Out[432]:
  3. int64 float64 bool1 bool2 tdeltas
  4. 0 1 4.0 True False NaT
  5. 1 2 5.0 False True 1 days
  6. 2 3 6.0 True False 1 days

To select string columns you must use the object dtype:

  1. In [433]: df.select_dtypes(include=['object'])
  2. Out[433]:
  3. string
  4. 0 a
  5. 1 b
  6. 2 c

To see all the child dtypes of a generic dtype like numpy.number you can define a function that returns a tree of child dtypes:

  1. In [434]: def subdtypes(dtype):
  2. .....: subs = dtype.__subclasses__()
  3. .....: if not subs:
  4. .....: return dtype
  5. .....: return [dtype, [subdtypes(dt) for dt in subs]]
  6. .....:

All NumPy dtypes are subclasses of numpy.generic:

  1. In [435]: subdtypes(np.generic)
  2. Out[435]:
  3. [numpy.generic,
  4. [[numpy.number,
  5. [[numpy.integer,
  6. [[numpy.signedinteger,
  7. [numpy.int8,
  8. numpy.int16,
  9. numpy.int32,
  10. numpy.int64,
  11. numpy.int64,
  12. numpy.timedelta64]],
  13. [numpy.unsignedinteger,
  14. [numpy.uint8,
  15. numpy.uint16,
  16. numpy.uint32,
  17. numpy.uint64,
  18. numpy.uint64]]]],
  19. [numpy.inexact,
  20. [[numpy.floating,
  21. [numpy.float16, numpy.float32, numpy.float64, numpy.float128]],
  22. [numpy.complexfloating,
  23. [numpy.complex64, numpy.complex128, numpy.complex256]]]]]],
  24. [numpy.flexible,
  25. [[numpy.character, [numpy.bytes_, numpy.str_]],
  26. [numpy.void, [numpy.record]]]],
  27. numpy.bool_,
  28. numpy.datetime64,
  29. numpy.object_]]

::: tip Note Pandas also defines the types category, and datetime64[ns, tz], which are not integrated into the normal NumPy hierarchy and won’t show up with the above function. :::