Essential basic functionality

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

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

Head and tail

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

  1. In [4]: long_series = pd.Series(np.random.randn(1000))
  2.  
  3. In [5]: long_series.head()
  4. Out[5]:
  5. 0 -1.157892
  6. 1 -1.344312
  7. 2 0.844885
  8. 3 1.075770
  9. 4 -0.109050
  10. dtype: float64
  11.  
  12. In [6]: long_series.tail(3)
  13. Out[6]:
  14. 997 -0.289388
  15. 998 -1.020544
  16. 999 0.589993
  17. 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

Note, these attributes can be safely assigned to!

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

Pandas objects (Index, Series, DataFrame) can bethought of as containers for arrays, which hold the actual data and do theactual computation. For many types, the underlying array is anumpy.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, usethe .array property

  1. In [10]: s.array
  2. Out[10]:
  3. <PandasArray>
  4. [ 0.4691122999071863, -0.2828633443286633, -1.5090585031735124,
  5. -1.1356323710171934, 1.2121120250208506]
  6. Length: 5, dtype: float64
  7.  
  8. In [11]: s.index.array
  9. Out[11]:
  10. <PandasArray>
  11. ['a', 'b', 'c', 'd', 'e']
  12. 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 bitbeyond 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 [12]: s.to_numpy()
  2. Out[12]: array([ 0.4691, -0.2829, -1.5091, -1.1356, 1.2121])
  3.  
  4. In [13]: np.asarray(s)
  5. Out[13]: array([ 0.4691, -0.2829, -1.5091, -1.1356, 1.2121])

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

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

  • An object-dtype numpy.ndarray with Timestamp objects, eachwith the correct tz
  • A datetime64[ns] -dtype numpy.ndarray, where the values havebeen converted to UTC and the timezone discardedTimezones may be preserved with dtype=object
  1. In [14]: ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
  2.  
  3. In [15]: ser.to_numpy(dtype=object)
  4. Out[15]:
  5. array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),
  6. Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],
  7. dtype=object)

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

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

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

  1. In [17]: df.to_numpy()
  2. Out[17]:
  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 contains homogeneously-typed data, the ndarray canactually be modified in-place, and the changes will be reflected in the datastructure. For heterogeneous data (e.g. some of the DataFrame’s columns are notall the same dtype), this will not be the case. The values attribute itself,unlike the axis labels, cannot be assigned to.

Note

When working with heterogeneous data, the dtype of the resulting ndarraywill be chosen to accommodate all of the data involved. For example, ifstrings are involved, the result will be of object dtype. If there are onlyfloats and integers, the resulting array will be of float dtype.

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

  • When your Series contains an extension type, it’sunclear whether Series.values returns a NumPy array or the extension array.Series.array will always return an ExtensionArray, and will nevercopy data. Series.to_numpy() will always return a NumPy array,potentially at the cost of copying / coercing values.
  • When your DataFrame contains a mixture of data types, DataFrame.values mayinvolve copying data and coercing values to a common dtype, a relatively expensiveoperation. DataFrame.to_numpy(), being a method, makes it clearer that thereturned 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 usingthe numexpr library and the bottleneck libraries.

These libraries are especially useful when dealing with large data sets, and provide largespeedups. numexpr uses smart chunking, caching, and multiple cores. bottleneck isa set of specialized cython routines that are especially fast when dealing with arrays that havenans.

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

Operation0.11.0 (ms)Prior Version (ms)Ratio to Prior
df1 > df213.32125.350.1063
df1 * df221.7136.630.5928
df1 + df222.0436.500.6039

You are highly encouraged to install both libraries. See the sectionRecommended 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 pointsof interest:

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

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

Matching / broadcasting behavior

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

  1. In [18]: 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.  
  7. In [19]: df
  8. Out[19]:
  9. one two three
  10. a 1.394981 1.772517 NaN
  11. b 0.343054 1.912123 -0.050390
  12. c 0.695246 1.478369 1.227435
  13. d NaN 0.279344 -0.613172
  14.  
  15. In [20]: row = df.iloc[1]
  16.  
  17. In [21]: column = df['two']
  18.  
  19. In [22]: df.sub(row, axis='columns')
  20. Out[22]:
  21. one two three
  22. a 1.051928 -0.139606 NaN
  23. b 0.000000 0.000000 0.000000
  24. c 0.352192 -0.433754 1.277825
  25. d NaN -1.632779 -0.562782
  26.  
  27. In [23]: df.sub(row, axis=1)
  28. Out[23]:
  29. one two three
  30. a 1.051928 -0.139606 NaN
  31. b 0.000000 0.000000 0.000000
  32. c 0.352192 -0.433754 1.277825
  33. d NaN -1.632779 -0.562782
  34.  
  35. In [24]: df.sub(column, axis='index')
  36. Out[24]:
  37. one two three
  38. a -0.377535 0.0 NaN
  39. b -1.569069 0.0 -1.962513
  40. c -0.783123 0.0 -0.250933
  41. d NaN 0.0 -0.892516
  42.  
  43. In [25]: df.sub(column, axis=0)
  44. Out[25]:
  45. one two three
  46. a -0.377535 0.0 NaN
  47. b -1.569069 0.0 -1.962513
  48. c -0.783123 0.0 -0.250933
  49. d NaN 0.0 -0.892516

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

  1. In [26]: dfmi = df.copy()
  2.  
  3. In [27]: dfmi.index = pd.MultiIndex.from_tuples([(1, 'a'), (1, 'b'),
  4. ....: (1, 'c'), (2, 'a')],
  5. ....: names=['first', 'second'])
  6. ....:
  7.  
  8. In [28]: dfmi.sub(column, axis=0, level='second')
  9. Out[28]:
  10. one two three
  11. first second
  12. 1 a -0.377535 0.000000 NaN
  13. b -1.569069 0.000000 -1.962513
  14. c -0.783123 0.000000 -0.250933
  15. 2 a NaN -1.493173 -2.385688

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

  1. In [29]: s = pd.Series(np.arange(10))
  2.  
  3. In [30]: s
  4. Out[30]:
  5. 0 0
  6. 1 1
  7. 2 2
  8. 3 3
  9. 4 4
  10. 5 5
  11. 6 6
  12. 7 7
  13. 8 8
  14. 9 9
  15. dtype: int64
  16.  
  17. In [31]: div, rem = divmod(s, 3)
  18.  
  19. In [32]: div
  20. Out[32]:
  21. 0 0
  22. 1 0
  23. 2 0
  24. 3 1
  25. 4 1
  26. 5 1
  27. 6 2
  28. 7 2
  29. 8 2
  30. 9 3
  31. dtype: int64
  32.  
  33. In [33]: rem
  34. Out[33]:
  35. 0 0
  36. 1 1
  37. 2 2
  38. 3 0
  39. 4 1
  40. 5 2
  41. 6 0
  42. 7 1
  43. 8 2
  44. 9 0
  45. dtype: int64
  46.  
  47. In [34]: idx = pd.Index(np.arange(10))
  48.  
  49. In [35]: idx
  50. Out[35]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')
  51.  
  52. In [36]: div, rem = divmod(idx, 3)
  53.  
  54. In [37]: div
  55. Out[37]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2, 3], dtype='int64')
  56.  
  57. In [38]: rem
  58. Out[38]: Int64Index([0, 1, 2, 0, 1, 2, 0, 1, 2, 0], dtype='int64')

We can also do elementwise divmod():

  1. In [39]: div, rem = divmod(s, [2, 2, 3, 3, 4, 4, 5, 5, 6, 6])
  2.  
  3. In [40]: div
  4. Out[40]:
  5. 0 0
  6. 1 0
  7. 2 0
  8. 3 1
  9. 4 1
  10. 5 1
  11. 6 1
  12. 7 1
  13. 8 1
  14. 9 1
  15. dtype: int64
  16.  
  17. In [41]: rem
  18. Out[41]:
  19. 0 0
  20. 1 1
  21. 2 2
  22. 3 0
  23. 4 0
  24. 5 1
  25. 6 1
  26. 7 2
  27. 8 2
  28. 9 3
  29. dtype: int64

Missing data / operations with fill values

In Series and DataFrame, the arithmetic functions have the option of inputtinga fill_value, namely a value to substitute when at most one of the values ata location are missing. For example, when adding two DataFrame objects, you maywish to treat NaN as 0 unless both DataFrames are missing that value, in whichcase the result will be NaN (you can later replace NaN with some other valueusing fillna if you wish).

  1. In [42]: df
  2. Out[42]:
  3. one two three
  4. a 1.394981 1.772517 NaN
  5. b 0.343054 1.912123 -0.050390
  6. c 0.695246 1.478369 1.227435
  7. d NaN 0.279344 -0.613172
  8.  
  9. In [43]: df2
  10. Out[43]:
  11. one two three
  12. a 1.394981 1.772517 1.000000
  13. b 0.343054 1.912123 -0.050390
  14. c 0.695246 1.478369 1.227435
  15. d NaN 0.279344 -0.613172
  16.  
  17. In [44]: df + df2
  18. Out[44]:
  19. one two three
  20. a 2.789963 3.545034 NaN
  21. b 0.686107 3.824246 -0.100780
  22. c 1.390491 2.956737 2.454870
  23. d NaN 0.558688 -1.226343
  24.  
  25. In [45]: df.add(df2, fill_value=0)
  26. Out[45]:
  27. one two three
  28. a 2.789963 3.545034 1.000000
  29. b 0.686107 3.824246 -0.100780
  30. c 1.390491 2.956737 2.454870
  31. d NaN 0.558688 -1.226343

Flexible comparisons

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

  1. In [46]: df.gt(df2)
  2. Out[46]:
  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.  
  9. In [47]: df2.ne(df)
  10. Out[47]:
  11. one two three
  12. a False False True
  13. b False False False
  14. c False False False
  15. d True False False

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

Boolean reductions

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

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

You can reduce to a final boolean value.

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

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

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

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

  1. In [53]: pd.Series([True]).bool()
  2. Out[53]: True
  3.  
  4. In [54]: pd.Series([False]).bool()
  5. Out[54]: False
  6.  
  7. In [55]: pd.DataFrame([[True]]).bool()
  8. Out[55]: True
  9.  
  10. In [56]: pd.DataFrame([[False]]).bool()
  11. Out[56]: False

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 sameresult. As a simple example, consider df + df and df 2. To testthat these two computations produce the same result, given the toolsshown above, you might imagine using (df + df == df 2).all(). But infact, this expression is False:

  1. In [57]: df + df == df * 2
  2. Out[57]:
  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.  
  9. In [58]: (df + df == df * 2).all()
  10. Out[58]:
  11. one False
  12. two True
  13. three False
  14. 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 [59]: np.nan == np.nan
  2. Out[59]: False

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

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

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

  1. In [61]: df1 = pd.DataFrame({'col': ['foo', 0, np.nan]})
  2.  
  3. In [62]: df2 = pd.DataFrame({'col': [np.nan, 0, 'foo']}, index=[2, 1, 0])
  4.  
  5. In [63]: df1.equals(df2)
  6. Out[63]: False
  7.  
  8. In [64]: df1.equals(df2.sort_index())
  9. Out[64]: True

Comparing array-like objects

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

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

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

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

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

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

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

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

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

  1. In [70]: np.array([1, 2, 3]) == np.array([1, 2])
  2. Out[70]: False

Combining overlapping data sets

A problem occasionally arising is the combination of two similar data setswhere values in one are preferred over the other. An example would be two dataseries representing a particular economic indicator where one is considered tobe of “higher quality”. However, the lower quality series might extend furtherback in history or have more complete data coverage. As such, we would like tocombine two DataFrame objects where missing values in one DataFrame areconditionally filled with like-labeled values from the other DataFrame. Thefunction implementing this operation is combine_first(),which we illustrate:

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

General DataFrame combine

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

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

  1. In [76]: 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 andother related operations on Series, DataFrame. Most of theseare aggregations (hence producing a lower-dimensional result) likesum(), mean(), and quantile(),but some of them, like cumsum() and cumprod(),produce an object of the same size. Generally speaking, these methods take anaxis argument, just like ndarray.{sum, std, …}, but the axis can bespecified by name or integer:

  • Series: no axis argument needed
  • DataFrame: “index” (axis=0, default), “columns” (axis=1)

For example:

  1. In [77]: df
  2. Out[77]:
  3. one two three
  4. a 1.394981 1.772517 NaN
  5. b 0.343054 1.912123 -0.050390
  6. c 0.695246 1.478369 1.227435
  7. d NaN 0.279344 -0.613172
  8.  
  9. In [78]: df.mean(0)
  10. Out[78]:
  11. one 0.811094
  12. two 1.360588
  13. three 0.187958
  14. dtype: float64
  15.  
  16. In [79]: df.mean(1)
  17. Out[79]:
  18. a 1.583749
  19. b 0.734929
  20. c 1.133683
  21. d -0.166914
  22. dtype: float64

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

  1. In [80]: df.sum(0, skipna=False)
  2. Out[80]:
  3. one NaN
  4. two 5.442353
  5. three NaN
  6. dtype: float64
  7.  
  8. In [81]: df.sum(axis=1, skipna=True)
  9. Out[81]:
  10. a 3.167498
  11. b 2.204786
  12. c 3.401050
  13. d -0.333828
  14. dtype: float64

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

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

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

  1. In [86]: df.cumsum()
  2. Out[86]:
  3. one two three
  4. a 1.394981 1.772517 NaN
  5. b 1.738035 3.684640 -0.050390
  6. c 2.433281 5.163008 1.177045
  7. d NaN 5.442353 0.563873

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

FunctionDescription
countNumber of non-NA observations
sumSum of values
meanMean of values
madMean absolute deviation
medianArithmetic median of values
minMinimum
maxMaximum
modeMode
absAbsolute Value
prodProduct of values
stdBessel-corrected sample standard deviation
varUnbiased variance
semStandard error of the mean
skewSample skewness (3rd moment)
kurtSample kurtosis (4th moment)
quantileSample quantile (value at %)
cumsumCumulative sum
cumprodCumulative product
cummaxCumulative maximum
cumminCumulative minimum

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

  1. In [87]: np.mean(df['one'])
  2. Out[87]: 0.8110935116651192
  3.  
  4. In [88]: np.mean(df['one'].to_numpy())
  5. Out[88]: nan

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

  1. In [89]: series = pd.Series(np.random.randn(500))
  2.  
  3. In [90]: series[20:500] = np.nan
  4.  
  5. In [91]: series[10:20] = 5
  6.  
  7. In [92]: series.nunique()
  8. Out[92]: 11

Summarizing data: describe

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

  1. In [93]: series = pd.Series(np.random.randn(1000))
  2.  
  3. In [94]: series[::2] = np.nan
  4.  
  5. In [95]: series.describe()
  6. Out[95]:
  7. count 500.000000
  8. mean -0.021292
  9. std 1.015906
  10. min -2.683763
  11. 25% -0.699070
  12. 50% -0.069718
  13. 75% 0.714483
  14. max 3.160915
  15. dtype: float64
  16.  
  17. In [96]: frame = pd.DataFrame(np.random.randn(1000, 5),
  18. ....: columns=['a', 'b', 'c', 'd', 'e'])
  19. ....:
  20.  
  21. In [97]: frame.iloc[::2] = np.nan
  22.  
  23. In [98]: frame.describe()
  24. Out[98]:
  25. a b c d e
  26. count 500.000000 500.000000 500.000000 500.000000 500.000000
  27. mean 0.033387 0.030045 -0.043719 -0.051686 0.005979
  28. std 1.017152 0.978743 1.025270 1.015988 1.006695
  29. min -3.000951 -2.637901 -3.303099 -3.159200 -3.188821
  30. 25% -0.647623 -0.576449 -0.712369 -0.691338 -0.691115
  31. 50% 0.047578 -0.021499 -0.023888 -0.032652 -0.025363
  32. 75% 0.729907 0.775880 0.618896 0.670047 0.649748
  33. max 2.740139 2.752332 3.004229 2.728702 3.240991

You can select specific percentiles to include in the output:

  1. In [99]: series.describe(percentiles=[.05, .25, .75, .95])
  2. Out[99]:
  3. count 500.000000
  4. mean -0.021292
  5. std 1.015906
  6. min -2.683763
  7. 5% -1.645423
  8. 25% -0.699070
  9. 50% -0.069718
  10. 75% 0.714483
  11. 95% 1.711409
  12. max 3.160915
  13. dtype: float64

By default, the median is always included.

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

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

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

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

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

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

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

Index of min/max values

The idxmin() and idxmax() functions on Seriesand DataFrame compute the index labels with the minimum and maximumcorresponding values:

  1. In [107]: s1 = pd.Series(np.random.randn(5))
  2.  
  3. In [108]: s1
  4. Out[108]:
  5. 0 1.118076
  6. 1 -0.352051
  7. 2 -1.242883
  8. 3 -1.277155
  9. 4 -0.641184
  10. dtype: float64
  11.  
  12. In [109]: s1.idxmin(), s1.idxmax()
  13. Out[109]: (3, 0)
  14.  
  15. In [110]: df1 = pd.DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])
  16.  
  17. In [111]: df1
  18. Out[111]:
  19. A B C
  20. 0 -0.327863 -0.946180 -0.137570
  21. 1 -0.186235 -0.257213 -0.486567
  22. 2 -0.507027 -0.871259 -0.111110
  23. 3 2.000339 -2.430505 0.089759
  24. 4 -0.321434 -0.033695 0.096271
  25.  
  26. In [112]: df1.idxmin(axis=0)
  27. Out[112]:
  28. A 2
  29. B 3
  30. C 1
  31. dtype: int64
  32.  
  33. In [113]: df1.idxmax(axis=1)
  34. Out[113]:
  35. 0 C
  36. 1 A
  37. 2 C
  38. 3 A
  39. 4 C
  40. dtype: object

When there are multiple rows (or columns) matching the minimum or maximumvalue, idxmin() and idxmax() return the firstmatching index:

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

Note

idxmin and idxmax are called argmin and argmax in NumPy.

Value counts (histogramming) / mode

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

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

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

  1. In [122]: s5 = pd.Series([1, 1, 3, 3, 3, 5, 5, 7, 7, 7])
  2.  
  3. In [123]: s5.mode()
  4. Out[123]:
  5. 0 3
  6. 1 7
  7. dtype: int64
  8.  
  9. In [124]: df5 = pd.DataFrame({"A": np.random.randint(0, 7, size=50),
  10. .....: "B": np.random.randint(-10, 15, size=50)})
  11. .....:
  12.  
  13. In [125]: df5.mode()
  14. Out[125]:
  15. A B
  16. 0 1.0 -9
  17. 1 NaN 10
  18. 2 NaN 13

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 [126]: arr = np.random.randn(20)
  2.  
  3. In [127]: factor = pd.cut(arr, 4)
  4.  
  5. In [128]: factor
  6. Out[128]:
  7. [(-0.251, 0.464], (-0.968, -0.251], (0.464, 1.179], (-0.251, 0.464], (-0.968, -0.251], ..., (-0.251, 0.464], (-0.968, -0.251], (-0.968, -0.251], (-0.968, -0.251], (-0.968, -0.251]]
  8. Length: 20
  9. Categories (4, interval[float64]): [(-0.968, -0.251] < (-0.251, 0.464] < (0.464, 1.179] <
  10. (1.179, 1.893]]
  11.  
  12. In [129]: factor = pd.cut(arr, [-5, -1, 0, 1, 5])
  13.  
  14. In [130]: factor
  15. Out[130]:
  16. [(0, 1], (-1, 0], (0, 1], (0, 1], (-1, 0], ..., (-1, 0], (-1, 0], (-1, 0], (-1, 0], (-1, 0]]
  17. Length: 20
  18. Categories (4, interval[int64]): [(-5, -1] < (-1, 0] < (0, 1] < (1, 5]]

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

  1. In [131]: arr = np.random.randn(30)
  2.  
  3. In [132]: factor = pd.qcut(arr, [0, .25, .5, .75, 1])
  4.  
  5. In [133]: factor
  6. Out[133]:
  7. [(0.569, 1.184], (-2.278, -0.301], (-2.278, -0.301], (0.569, 1.184], (0.569, 1.184], ..., (-0.301, 0.569], (1.184, 2.346], (1.184, 2.346], (-0.301, 0.569], (-2.278, -0.301]]
  8. Length: 30
  9. Categories (4, interval[float64]): [(-2.278, -0.301] < (-0.301, 0.569] < (0.569, 1.184] <
  10. (1.184, 2.346]]
  11.  
  12. In [134]: pd.value_counts(factor)
  13. Out[134]:
  14. (1.184, 2.346] 8
  15. (-2.278, -0.301] 8
  16. (0.569, 1.184] 7
  17. (-0.301, 0.569] 7
  18. dtype: int64

We can also pass infinite values to define the bins:

  1. In [135]: arr = np.random.randn(20)
  2.  
  3. In [136]: factor = pd.cut(arr, [-np.inf, 0, np.inf])
  4.  
  5. In [137]: factor
  6. Out[137]:
  7. [(-inf, 0.0], (0.0, inf], (0.0, inf], (-inf, 0.0], (-inf, 0.0], ..., (-inf, 0.0], (-inf, 0.0], (-inf, 0.0], (0.0, inf], (0.0, inf]]
  8. Length: 20
  9. 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 appropriatemethod to use depends on whether your function expects to operateon an entire DataFrame or Series, row- or column-wise, or elementwise.

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

The pipe method is inspired by unix pipes and more recently dplyr and magrittr, whichhave 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 DataFrameusing the apply() method, which, like the descriptivestatistics methods, takes an optional axis argument:

  1. In [141]: df.apply(np.mean)
  2. Out[141]:
  3. one 0.811094
  4. two 1.360588
  5. three 0.187958
  6. dtype: float64
  7.  
  8. In [142]: df.apply(np.mean, axis=1)
  9. Out[142]:
  10. a 1.583749
  11. b 0.734929
  12. c 1.133683
  13. d -0.166914
  14. dtype: float64
  15.  
  16. In [143]: df.apply(lambda x: x.max() - x.min())
  17. Out[143]:
  18. one 1.051928
  19. two 1.632779
  20. three 1.840607
  21. dtype: float64
  22.  
  23. In [144]: df.apply(np.cumsum)
  24. Out[144]:
  25. one two three
  26. a 1.394981 1.772517 NaN
  27. b 1.738035 3.684640 -0.050390
  28. c 2.433281 5.163008 1.177045
  29. d NaN 5.442353 0.563873
  30.  
  31. In [145]: df.apply(np.exp)
  32. Out[145]:
  33. one two three
  34. a 4.034899 5.885648 NaN
  35. b 1.409244 6.767440 0.950858
  36. c 2.004201 4.385785 3.412466
  37. d NaN 1.322262 0.541630

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

  1. In [146]: df.apply('mean')
  2. Out[146]:
  3. one 0.811094
  4. two 1.360588
  5. three 0.187958
  6. dtype: float64
  7.  
  8. In [147]: df.apply('mean', axis=1)
  9. Out[147]:
  10. a 1.583749
  11. b 0.734929
  12. c 1.133683
  13. d -0.166914
  14. dtype: float64

The return type of the function passed to apply() affects thetype 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, whichaccepts 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 questionsabout a data set. For example, suppose we wanted to extract the date where themaximum value for each column occurred:

  1. In [148]: tsdf = pd.DataFrame(np.random.randn(1000, 3), columns=['A', 'B', 'C'],
  2. .....: index=pd.date_range('1/1/2000', periods=1000))
  3. .....:
  4.  
  5. In [149]: tsdf.apply(lambda x: x.idxmax())
  6. Out[149]:
  7. A 2000-08-06
  8. B 2001-01-18
  9. C 2001-07-18
  10. dtype: datetime64[ns]

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

  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 someSeries operation on each column or row:

  1. In [150]: tsdf
  2. Out[150]:
  3. A B C
  4. 2000-01-01 -0.158131 -0.232466 0.321604
  5. 2000-01-02 -1.810340 -3.105758 0.433834
  6. 2000-01-03 -1.209847 -1.156793 -0.136794
  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.653602 0.178875 1.008298
  12. 2000-01-09 1.007996 0.462824 0.254472
  13. 2000-01-10 0.307473 0.600337 1.643950
  14.  
  15. In [151]: tsdf.apply(pd.Series.interpolate)
  16. Out[151]:
  17. A B C
  18. 2000-01-01 -0.158131 -0.232466 0.321604
  19. 2000-01-02 -1.810340 -3.105758 0.433834
  20. 2000-01-03 -1.209847 -1.156793 -0.136794
  21. 2000-01-04 -1.098598 -0.889659 0.092225
  22. 2000-01-05 -0.987349 -0.622526 0.321243
  23. 2000-01-06 -0.876100 -0.355392 0.550262
  24. 2000-01-07 -0.764851 -0.088259 0.779280
  25. 2000-01-08 -0.653602 0.178875 1.008298
  26. 2000-01-09 1.007996 0.462824 0.254472
  27. 2000-01-10 0.307473 0.600337 1.643950

Finally, apply() takes an argument raw which is False by default, whichconverts each row or column into a Series before applying the function. Whenset to True, the passed function will instead receive an ndarray object, whichhas positive performance implications if you do not need the indexingfunctionality.

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, thewindow functions API, and the resample API.The entry point for aggregation is DataFrame.aggregate(), or the aliasDataFrame.agg().

We will use a similar starting frame from above:

  1. In [152]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],
  2. .....: index=pd.date_range('1/1/2000', periods=10))
  3. .....:
  4.  
  5. In [153]: tsdf.iloc[3:7] = np.nan
  6.  
  7. In [154]: tsdf
  8. Out[154]:
  9. A B C
  10. 2000-01-01 1.257606 1.004194 0.167574
  11. 2000-01-02 -0.749892 0.288112 -0.757304
  12. 2000-01-03 -0.207550 -0.298599 0.116018
  13. 2000-01-04 NaN NaN NaN
  14. 2000-01-05 NaN NaN NaN
  15. 2000-01-06 NaN NaN NaN
  16. 2000-01-07 NaN NaN NaN
  17. 2000-01-08 0.814347 -0.257623 0.869226
  18. 2000-01-09 -0.250663 -1.206601 0.896839
  19. 2000-01-10 2.169758 -1.333363 0.283157

Using a single function is equivalent to apply(). You can alsopass named methods as strings. These will return a Series of the aggregatedoutput:

  1. In [155]: tsdf.agg(np.sum)
  2. Out[155]:
  3. A 3.033606
  4. B -1.803879
  5. C 1.575510
  6. dtype: float64
  7.  
  8. In [156]: tsdf.agg('sum')
  9. Out[156]:
  10. A 3.033606
  11. B -1.803879
  12. C 1.575510
  13. dtype: float64
  14.  
  15. # these are equivalent to a ``.sum()`` because we are aggregating
  16. # on a single function
  17. In [157]: tsdf.sum()
  18. Out[157]:
  19. A 3.033606
  20. B -1.803879
  21. C 1.575510
  22. dtype: float64

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

  1. In [158]: tsdf.A.agg('sum')
  2. Out[158]: 3.033606102414146

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 [159]: tsdf.agg(['sum'])
  2. Out[159]:
  3. A B C
  4. sum 3.033606 -1.803879 1.57551

Multiple functions yield multiple rows:

  1. In [160]: tsdf.agg(['sum', 'mean'])
  2. Out[160]:
  3. A B C
  4. sum 3.033606 -1.803879 1.575510
  5. mean 0.505601 -0.300647 0.262585

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

  1. In [161]: tsdf.A.agg(['sum', 'mean'])
  2. Out[161]:
  3. sum 3.033606
  4. mean 0.505601
  5. Name: A, dtype: float64

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

  1. In [162]: tsdf.A.agg(['sum', lambda x: x.mean()])
  2. Out[162]:
  3. sum 3.033606
  4. <lambda> 0.505601
  5. Name: A, dtype: float64

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

  1. In [163]: def mymean(x):
  2. .....: return x.mean()
  3. .....:
  4.  
  5. In [164]: tsdf.A.agg(['sum', mymean])
  6. Out[164]:
  7. sum 3.033606
  8. mymean 0.505601
  9. Name: A, dtype: float64

Aggregating with a dict

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

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

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

  1. In [166]: tsdf.agg({'A': ['mean', 'min'], 'B': 'sum'})
  2. Out[166]:
  3. A B
  4. mean 0.505601 NaN
  5. min -0.749892 NaN
  6. sum NaN -1.803879

Mixed dtypes

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

  1. In [167]: 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.  
  7. In [168]: mdf.dtypes
  8. Out[168]:
  9. A int64
  10. B float64
  11. C object
  12. D datetime64[ns]
  13. dtype: object
  1. In [169]: mdf.agg(['min', 'sum'])
  2. Out[169]:
  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, similarto the built in describe function.

  1. In [170]: from functools import partial
  2.  
  3. In [171]: q_25 = partial(pd.Series.quantile, q=0.25)
  4.  
  5. In [172]: q_25.__name__ = '25%'
  6.  
  7. In [173]: q_75 = partial(pd.Series.quantile, q=0.75)
  8.  
  9. In [174]: q_75.__name__ = '75%'
  10.  
  11. In [175]: tsdf.agg(['count', 'mean', 'std', 'min', q_25, 'median', q_75, 'max'])
  12. Out[175]:
  13. A B C
  14. count 6.000000 6.000000 6.000000
  15. mean 0.505601 -0.300647 0.262585
  16. std 1.103362 0.887508 0.606860
  17. min -0.749892 -1.333363 -0.757304
  18. 25% -0.239885 -0.979600 0.128907
  19. median 0.303398 -0.278111 0.225365
  20. 75% 1.146791 0.151678 0.722709
  21. max 2.169758 1.004194 0.896839

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 sametime 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 [176]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],
  2. .....: index=pd.date_range('1/1/2000', periods=10))
  3. .....:
  4.  
  5. In [177]: tsdf.iloc[3:7] = np.nan
  6.  
  7. In [178]: tsdf
  8. Out[178]:
  9. A B C
  10. 2000-01-01 -0.428759 -0.864890 -0.675341
  11. 2000-01-02 -0.168731 1.338144 -1.279321
  12. 2000-01-03 -1.621034 0.438107 0.903794
  13. 2000-01-04 NaN NaN NaN
  14. 2000-01-05 NaN NaN NaN
  15. 2000-01-06 NaN NaN NaN
  16. 2000-01-07 NaN NaN NaN
  17. 2000-01-08 0.254374 -1.240447 -0.201052
  18. 2000-01-09 -0.157795 0.791197 -1.144209
  19. 2000-01-10 -0.030876 0.371900 0.061932

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

  1. In [179]: tsdf.transform(np.abs)
  2. Out[179]:
  3. A B C
  4. 2000-01-01 0.428759 0.864890 0.675341
  5. 2000-01-02 0.168731 1.338144 1.279321
  6. 2000-01-03 1.621034 0.438107 0.903794
  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.254374 1.240447 0.201052
  12. 2000-01-09 0.157795 0.791197 1.144209
  13. 2000-01-10 0.030876 0.371900 0.061932
  14.  
  15. In [180]: tsdf.transform('abs')
  16. Out[180]:
  17. A B C
  18. 2000-01-01 0.428759 0.864890 0.675341
  19. 2000-01-02 0.168731 1.338144 1.279321
  20. 2000-01-03 1.621034 0.438107 0.903794
  21. 2000-01-04 NaN NaN NaN
  22. 2000-01-05 NaN NaN NaN
  23. 2000-01-06 NaN NaN NaN
  24. 2000-01-07 NaN NaN NaN
  25. 2000-01-08 0.254374 1.240447 0.201052
  26. 2000-01-09 0.157795 0.791197 1.144209
  27. 2000-01-10 0.030876 0.371900 0.061932
  28.  
  29. In [181]: tsdf.transform(lambda x: x.abs())
  30. Out[181]:
  31. A B C
  32. 2000-01-01 0.428759 0.864890 0.675341
  33. 2000-01-02 0.168731 1.338144 1.279321
  34. 2000-01-03 1.621034 0.438107 0.903794
  35. 2000-01-04 NaN NaN NaN
  36. 2000-01-05 NaN NaN NaN
  37. 2000-01-06 NaN NaN NaN
  38. 2000-01-07 NaN NaN NaN
  39. 2000-01-08 0.254374 1.240447 0.201052
  40. 2000-01-09 0.157795 0.791197 1.144209
  41. 2000-01-10 0.030876 0.371900 0.061932

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

  1. In [182]: np.abs(tsdf)
  2. Out[182]:
  3. A B C
  4. 2000-01-01 0.428759 0.864890 0.675341
  5. 2000-01-02 0.168731 1.338144 1.279321
  6. 2000-01-03 1.621034 0.438107 0.903794
  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.254374 1.240447 0.201052
  12. 2000-01-09 0.157795 0.791197 1.144209
  13. 2000-01-10 0.030876 0.371900 0.061932

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

  1. In [183]: tsdf.A.transform(np.abs)
  2. Out[183]:
  3. 2000-01-01 0.428759
  4. 2000-01-02 0.168731
  5. 2000-01-03 1.621034
  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.254374
  11. 2000-01-09 0.157795
  12. 2000-01-10 0.030876
  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 levelwill be the names of the transforming functions.

  1. In [184]: tsdf.transform([np.abs, lambda x: x + 1])
  2. Out[184]:
  3. A B C
  4. absolute <lambda> absolute <lambda> absolute <lambda>
  5. 2000-01-01 0.428759 0.571241 0.864890 0.135110 0.675341 0.324659
  6. 2000-01-02 0.168731 0.831269 1.338144 2.338144 1.279321 -0.279321
  7. 2000-01-03 1.621034 -0.621034 0.438107 1.438107 0.903794 1.903794
  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.254374 1.254374 1.240447 -0.240447 0.201052 0.798948
  13. 2000-01-09 0.157795 0.842205 0.791197 1.791197 1.144209 -0.144209
  14. 2000-01-10 0.030876 0.969124 0.371900 1.371900 0.061932 1.061932

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

  1. In [185]: tsdf.A.transform([np.abs, lambda x: x + 1])
  2. Out[185]:
  3. absolute <lambda>
  4. 2000-01-01 0.428759 0.571241
  5. 2000-01-02 0.168731 0.831269
  6. 2000-01-03 1.621034 -0.621034
  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.254374 1.254374
  12. 2000-01-09 0.157795 0.842205
  13. 2000-01-10 0.030876 0.969124

Transforming with a dict

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

  1. In [186]: tsdf.transform({'A': np.abs, 'B': lambda x: x + 1})
  2. Out[186]:
  3. A B
  4. 2000-01-01 0.428759 0.135110
  5. 2000-01-02 0.168731 2.338144
  6. 2000-01-03 1.621034 1.438107
  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.254374 -0.240447
  12. 2000-01-09 0.157795 1.791197
  13. 2000-01-10 0.030876 1.371900

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

  1. In [187]: tsdf.transform({'A': np.abs, 'B': [lambda x: x + 1, 'sqrt']})
  2. Out[187]:
  3. A B
  4. absolute <lambda> sqrt
  5. 2000-01-01 0.428759 0.135110 NaN
  6. 2000-01-02 0.168731 2.338144 1.156782
  7. 2000-01-03 1.621034 1.438107 0.661897
  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.254374 -0.240447 NaN
  13. 2000-01-09 0.157795 1.791197 0.889493
  14. 2000-01-10 0.030876 1.371900 0.609836

Applying elementwise functions

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

  1. In [188]: df4
  2. Out[188]:
  3. one two three
  4. a 1.394981 1.772517 NaN
  5. b 0.343054 1.912123 -0.050390
  6. c 0.695246 1.478369 1.227435
  7. d NaN 0.279344 -0.613172
  8.  
  9. In [189]: def f(x):
  10. .....: return len(str(x))
  11. .....:
  12.  
  13. In [190]: df4['one'].map(f)
  14. Out[190]:
  15. a 18
  16. b 19
  17. c 18
  18. d 3
  19. Name: one, dtype: int64
  20.  
  21. In [191]: df4.applymap(f)
  22. Out[191]:
  23. one two three
  24. a 18 17 3
  25. b 19 18 20
  26. c 18 18 16
  27. d 3 19 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 relatedto merging/joining functionality:

  1. In [192]: s = pd.Series(['six', 'seven', 'six', 'seven', 'six'],
  2. .....: index=['a', 'b', 'c', 'd', 'e'])
  3. .....:
  4.  
  5. In [193]: t = pd.Series({'six': 6., 'seven': 7.})
  6.  
  7. In [194]: s
  8. Out[194]:
  9. a six
  10. b seven
  11. c six
  12. d seven
  13. e six
  14. dtype: object
  15.  
  16. In [195]: s.map(t)
  17. Out[195]:
  18. a 6.0
  19. b 7.0
  20. c 6.0
  21. d 7.0
  22. e 6.0
  23. 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-alignmentfunctionality. To reindex means to conform the data to match a given set oflabels 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 forthat label existed
  • If specified, fill data for missing labels using logic (highly relevantto working with time series data)

Here is a simple example:

  1. In [196]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
  2.  
  3. In [197]: s
  4. Out[197]:
  5. a 1.695148
  6. b 1.328614
  7. c 1.234686
  8. d -0.385845
  9. e -1.326508
  10. dtype: float64
  11.  
  12. In [198]: s.reindex(['e', 'b', 'f', 'd'])
  13. Out[198]:
  14. e -1.326508
  15. b 1.328614
  16. f NaN
  17. d -0.385845
  18. dtype: float64

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

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

  1. In [199]: df
  2. Out[199]:
  3. one two three
  4. a 1.394981 1.772517 NaN
  5. b 0.343054 1.912123 -0.050390
  6. c 0.695246 1.478369 1.227435
  7. d NaN 0.279344 -0.613172
  8.  
  9. In [200]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
  10. Out[200]:
  11. three two one
  12. c 1.227435 1.478369 0.695246
  13. f NaN NaN NaN
  14. b -0.050390 1.912123 0.343054

You may also use reindex with an axis keyword:

  1. In [201]: df.reindex(['c', 'f', 'b'], axis='index')
  2. Out[201]:
  3. one two three
  4. c 0.695246 1.478369 1.227435
  5. f NaN NaN NaN
  6. b 0.343054 1.912123 -0.050390

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

  1. In [202]: rs = s.reindex(df.index)
  2.  
  3. In [203]: rs
  4. Out[203]:
  5. a 1.695148
  6. b 1.328614
  7. c 1.234686
  8. d -0.385845
  9. dtype: float64
  10.  
  11. In [204]: rs.index is df.index
  12. Out[204]: True

This means that the reindexed Series’s index is the same Python object as theDataFrame’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 [205]: df.reindex(['c', 'f', 'b'], axis='index')
  2. Out[205]:
  3. one two three
  4. c 0.695246 1.478369 1.227435
  5. f NaN NaN NaN
  6. b 0.343054 1.912123 -0.050390
  7.  
  8. In [206]: df.reindex(['three', 'two', 'one'], axis='columns')
  9. Out[206]:
  10. three two one
  11. a NaN 1.772517 1.394981
  12. b -0.050390 1.912123 0.343054
  13. c 1.227435 1.478369 0.695246
  14. d -0.613172 0.279344 NaN

See also

MultiIndex / Advanced Indexing is an even more concise way ofdoing reindexing.

Note

When writing performance-sensitive code, there is a good reason to spendsome time becoming a reindexing ninja: many operations are faster onpre-aligned data. Adding two unaligned DataFrames internally triggers areindexing step. For exploratory analysis you will hardly notice thedifference (because reindex has been heavily optimized), but when CPUcycles matter sprinkling a few explicit reindex calls here and there canhave an impact.

Reindexing to align with another object

You may wish to take an object and reindex its axes to be labeled the same asanother object. While the syntax for this is straightforward albeit verbose, itis a common enough operation that the reindex_like() method isavailable to make this simpler:

  1. In [207]: df2
  2. Out[207]:
  3. one two
  4. a 1.394981 1.772517
  5. b 0.343054 1.912123
  6. c 0.695246 1.478369
  7.  
  8. In [208]: df3
  9. Out[208]:
  10. one two
  11. a 0.583888 0.051514
  12. b -0.468040 0.191120
  13. c -0.115848 -0.242634
  14.  
  15. In [209]: df.reindex_like(df2)
  16. Out[209]:
  17. one two
  18. a 1.394981 1.772517
  19. b 0.343054 1.912123
  20. c 0.695246 1.478369

Aligning objects with each other with align

The align() method is the fastest way to simultaneously align two objects. Itsupports 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 [210]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
  2.  
  3. In [211]: s1 = s[:4]
  4.  
  5. In [212]: s2 = s[1:]
  6.  
  7. In [213]: s1.align(s2)
  8. Out[213]:
  9. (a -0.186646
  10. b -1.692424
  11. c -0.303893
  12. d -1.425662
  13. e NaN
  14. dtype: float64, a NaN
  15. b -1.692424
  16. c -0.303893
  17. d -1.425662
  18. e 1.114285
  19. dtype: float64)
  20.  
  21. In [214]: s1.align(s2, join='inner')
  22. Out[214]:
  23. (b -1.692424
  24. c -0.303893
  25. d -1.425662
  26. dtype: float64, b -1.692424
  27. c -0.303893
  28. d -1.425662
  29. dtype: float64)
  30.  
  31. In [215]: s1.align(s2, join='left')
  32. Out[215]:
  33. (a -0.186646
  34. b -1.692424
  35. c -0.303893
  36. d -1.425662
  37. dtype: float64, a NaN
  38. b -1.692424
  39. c -0.303893
  40. d -1.425662
  41. dtype: float64)

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

  1. In [216]: df.align(df2, join='inner')
  2. Out[216]:
  3. ( one two
  4. a 1.394981 1.772517
  5. b 0.343054 1.912123
  6. c 0.695246 1.478369, one two
  7. a 1.394981 1.772517
  8. b 0.343054 1.912123
  9. c 0.695246 1.478369)

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

  1. In [217]: df.align(df2, join='inner', axis=0)
  2. Out[217]:
  3. ( one two three
  4. a 1.394981 1.772517 NaN
  5. b 0.343054 1.912123 -0.050390
  6. c 0.695246 1.478369 1.227435, one two
  7. a 1.394981 1.772517
  8. b 0.343054 1.912123
  9. c 0.695246 1.478369)

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

  1. In [218]: df.align(df2.iloc[0], axis=1)
  2. Out[218]:
  3. ( one three two
  4. a 1.394981 NaN 1.772517
  5. b 0.343054 -0.050390 1.912123
  6. c 0.695246 1.227435 1.478369
  7. d NaN -0.613172 0.279344, one 1.394981
  8. three NaN
  9. two 1.772517
  10. Name: a, dtype: float64)

Filling while reindexing

reindex() takes an optional parameter method which is afilling method chosen from the following table:

MethodAction
pad / ffillFill values forward
bfill / backfillFill values backward
nearestFill from the nearest index value

We illustrate these fill methods on a simple Series:

  1. In [219]: rng = pd.date_range('1/3/2000', periods=8)
  2.  
  3. In [220]: ts = pd.Series(np.random.randn(8), index=rng)
  4.  
  5. In [221]: ts2 = ts[[0, 3, 6]]
  6.  
  7. In [222]: ts
  8. Out[222]:
  9. 2000-01-03 0.183051
  10. 2000-01-04 0.400528
  11. 2000-01-05 -0.015083
  12. 2000-01-06 2.395489
  13. 2000-01-07 1.414806
  14. 2000-01-08 0.118428
  15. 2000-01-09 0.733639
  16. 2000-01-10 -0.936077
  17. Freq: D, dtype: float64
  18.  
  19. In [223]: ts2
  20. Out[223]:
  21. 2000-01-03 0.183051
  22. 2000-01-06 2.395489
  23. 2000-01-09 0.733639
  24. dtype: float64
  25.  
  26. In [224]: ts2.reindex(ts.index)
  27. Out[224]:
  28. 2000-01-03 0.183051
  29. 2000-01-04 NaN
  30. 2000-01-05 NaN
  31. 2000-01-06 2.395489
  32. 2000-01-07 NaN
  33. 2000-01-08 NaN
  34. 2000-01-09 0.733639
  35. 2000-01-10 NaN
  36. Freq: D, dtype: float64
  37.  
  38. In [225]: ts2.reindex(ts.index, method='ffill')
  39. Out[225]:
  40. 2000-01-03 0.183051
  41. 2000-01-04 0.183051
  42. 2000-01-05 0.183051
  43. 2000-01-06 2.395489
  44. 2000-01-07 2.395489
  45. 2000-01-08 2.395489
  46. 2000-01-09 0.733639
  47. 2000-01-10 0.733639
  48. Freq: D, dtype: float64
  49.  
  50. In [226]: ts2.reindex(ts.index, method='bfill')
  51. Out[226]:
  52. 2000-01-03 0.183051
  53. 2000-01-04 2.395489
  54. 2000-01-05 2.395489
  55. 2000-01-06 2.395489
  56. 2000-01-07 0.733639
  57. 2000-01-08 0.733639
  58. 2000-01-09 0.733639
  59. 2000-01-10 NaN
  60. Freq: D, dtype: float64
  61.  
  62. In [227]: ts2.reindex(ts.index, method='nearest')
  63. Out[227]:
  64. 2000-01-03 0.183051
  65. 2000-01-04 0.183051
  66. 2000-01-05 2.395489
  67. 2000-01-06 2.395489
  68. 2000-01-07 2.395489
  69. 2000-01-08 0.733639
  70. 2000-01-09 0.733639
  71. 2000-01-10 0.733639
  72. Freq: D, dtype: float64

These methods require that the indexes are ordered increasing ordecreasing.

Note that the same result could have been achieved usingfillna (except for method='nearest') orinterpolate:

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

reindex() will raise a ValueError if the index is not monotonicallyincreasing 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 overfilling while reindexing. Limit specifies the maximum count of consecutivematches:

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

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

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

Notice that when used on a DatetimeIndex, TimedeltaIndex orPeriodIndex, 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 [231]: df
  2. Out[231]:
  3. one two three
  4. a 1.394981 1.772517 NaN
  5. b 0.343054 1.912123 -0.050390
  6. c 0.695246 1.478369 1.227435
  7. d NaN 0.279344 -0.613172
  8.  
  9. In [232]: df.drop(['a', 'd'], axis=0)
  10. Out[232]:
  11. one two three
  12. b 0.343054 1.912123 -0.050390
  13. c 0.695246 1.478369 1.227435
  14.  
  15. In [233]: df.drop(['one'], axis=1)
  16. Out[233]:
  17. two three
  18. a 1.772517 NaN
  19. b 1.912123 -0.050390
  20. c 1.478369 1.227435
  21. d 0.279344 -0.613172

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

  1. In [234]: df.reindex(df.index.difference(['a', 'd']))
  2. Out[234]:
  3. one two three
  4. b 0.343054 1.912123 -0.050390
  5. c 0.695246 1.478369 1.227435

Renaming / mapping labels

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

  1. In [235]: s
  2. Out[235]:
  3. a -0.186646
  4. b -1.692424
  5. c -0.303893
  6. d -1.425662
  7. e 1.114285
  8. dtype: float64
  9.  
  10. In [236]: s.rename(str.upper)
  11. Out[236]:
  12. A -0.186646
  13. B -1.692424
  14. C -0.303893
  15. D -1.425662
  16. E 1.114285
  17. dtype: float64

If you pass a function, it must return a value when called with any of thelabels (and must produce a set of unique values). A dict orSeries can also be used:

  1. In [237]: df.rename(columns={'one': 'foo', 'two': 'bar'},
  2. .....: index={'a': 'apple', 'b': 'banana', 'd': 'durian'})
  3. .....:
  4. Out[237]:
  5. foo bar three
  6. apple 1.394981 1.772517 NaN
  7. banana 0.343054 1.912123 -0.050390
  8. c 0.695246 1.478369 1.227435
  9. durian NaN 0.279344 -0.613172

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

New in version 0.21.0.

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

  1. In [238]: df.rename({'one': 'foo', 'two': 'bar'}, axis='columns')
  2. Out[238]:
  3. foo bar three
  4. a 1.394981 1.772517 NaN
  5. b 0.343054 1.912123 -0.050390
  6. c 0.695246 1.478369 1.227435
  7. d NaN 0.279344 -0.613172
  8.  
  9. In [239]: df.rename({'a': 'apple', 'b': 'banana', 'd': 'durian'}, axis='index')
  10. Out[239]:
  11. one two three
  12. apple 1.394981 1.772517 NaN
  13. banana 0.343054 1.912123 -0.050390
  14. c 0.695246 1.478369 1.227435
  15. durian NaN 0.279344 -0.613172

The rename() method also provides an inplace namedparameter that is by default False and copies the underlying data. Passinplace=True to rename the data in place.

New in version 0.18.0.

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

  1. In [240]: s.rename("scalar-name")
  2. Out[240]:
  3. a -0.186646
  4. b -1.692424
  5. c -0.303893
  6. d -1.425662
  7. e 1.114285
  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 thelabels).

  1. In [241]: 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.  
  7. In [242]: df
  8. Out[242]:
  9. x y
  10. let num
  11. a 1 1 10
  12. 2 2 20
  13. b 1 3 30
  14. 2 4 40
  15. c 1 5 50
  16. 2 6 60
  17.  
  18. In [243]: df.rename_axis(index={'let': 'abc'})
  19. Out[243]:
  20. x y
  21. abc num
  22. a 1 1 10
  23. 2 2 20
  24. b 1 3 30
  25. 2 4 40
  26. c 1 5 50
  27. 2 6 60
  28.  
  29. In [244]: df.rename_axis(index=str.upper)
  30. Out[244]:
  31. x y
  32. LET NUM
  33. a 1 1 10
  34. 2 2 20
  35. b 1 3 30
  36. 2 4 40
  37. c 1 5 50
  38. 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 iterationproduces the values. DataFrames follow the dict-like convention of iteratingover the “keys” of the objects.

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

  • Series: values
  • DataFrame: column labels

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

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

Pandas objects also have the dict-like items() method toiterate 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 someperformance implications.
  • itertuples(): Iterate over the rows of a DataFrameas namedtuples of the values. This is a lot faster thaniterrows(), and is in most cases preferable to useto iterate over the values of a DataFrame.

Warning

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

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

Warning

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

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

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

items

Consistent with the dict-like interface, items() iteratesthrough key-value pairs:

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

For example:

  1. In [250]: for label, ser in df.items():
  2. .....: print(label)
  3. .....: print(ser)
  4. .....:
  5. a
  6. 0 1
  7. 1 2
  8. 2 3
  9. Name: a, dtype: int64
  10. b
  11. 0 a
  12. 1 b
  13. 2 c
  14. Name: b, dtype: object

iterrows

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

  1. In [251]: 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

Note

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

  1. In [252]: df_orig = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])
  2.  
  3. In [253]: df_orig.dtypes
  4. Out[253]:
  5. int int64
  6. float float64
  7. dtype: object
  8.  
  9. In [254]: row = next(df_orig.iterrows())[1]
  10.  
  11. In [255]: row
  12. Out[255]:
  13. int 1.0
  14. float 1.5
  15. Name: 0, dtype: float64

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

  1. In [256]: row['int'].dtype
  2. Out[256]: dtype('float64')
  3.  
  4. In [257]: df_orig['int'].dtype
  5. Out[257]: dtype('int64')

To preserve dtypes while iterating over the rows, it is betterto use itertuples() which returns namedtuples of the valuesand which is generally much faster than iterrows().

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

  1. In [258]: df2 = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
  2.  
  3. In [259]: print(df2)
  4. x y
  5. 0 1 4
  6. 1 2 5
  7. 2 3 6
  8.  
  9. In [260]: print(df2.T)
  10. 0 1 2
  11. x 1 2 3
  12. y 4 5 6
  13.  
  14. In [261]: df2_t = pd.DataFrame({idx: values for idx, values in df2.iterrows()})
  15.  
  16. In [262]: print(df2_t)
  17. 0 1 2
  18. x 1 2 3
  19. y 4 5 6

itertuples

The itertuples() method will return an iteratoryielding a namedtuple for each row in the DataFrame. The first elementof the tuple will be the row’s corresponding index value, while theremaining values are the row values.

For instance:

  1. In [263]: 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 merelyreturns the values inside a namedtuple. Therefore,itertuples() preserves the data type of the valuesand is generally faster as iterrows().

Note

The column names will be renamed to positional names if they areinvalid 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 thevalues 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 [264]: s = pd.Series(pd.date_range('20130101 09:10:12', periods=4))
  3.  
  4. In [265]: s
  5. Out[265]:
  6. 0 2013-01-01 09:10:12
  7. 1 2013-01-02 09:10:12
  8. 2 2013-01-03 09:10:12
  9. 3 2013-01-04 09:10:12
  10. dtype: datetime64[ns]
  11.  
  12. In [266]: s.dt.hour
  13. Out[266]:
  14. 0 9
  15. 1 9
  16. 2 9
  17. 3 9
  18. dtype: int64
  19.  
  20. In [267]: s.dt.second
  21. Out[267]:
  22. 0 12
  23. 1 12
  24. 2 12
  25. 3 12
  26. dtype: int64
  27.  
  28. In [268]: s.dt.day
  29. Out[268]:
  30. 0 1
  31. 1 2
  32. 2 3
  33. 3 4
  34. dtype: int64

This enables nice expressions like this:

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

You can easily produces tz aware transformations:

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

You can also chain these types of operations:

  1. In [273]: s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
  2. Out[273]:
  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() whichsupports the same format as the standard strftime().

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

The .dt accessor works for period and timedelta dtypes.

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

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 tooperate on each element of the array. Perhaps most importantly, these methodsexclude missing/NA values automatically. These are accessed via the Series’sstr attribute and generally have names matching the equivalent (scalar)built-in string methods. For example:

  1. In [289]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])In [290]: s.str.lower()Out[290]:0 a1 b2 c3 aaba4 baca5 NaN6 caba7 dog8 catdtype: object

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

Please see Vectorized String Methods for a completedescription.

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 areused to sort a pandas object by its index levels.

  1. In [291]: 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.  
  7. In [292]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
  8. .....: columns=['three', 'two', 'one'])
  9. .....:
  10.  
  11. In [293]: unsorted_df
  12. Out[293]:
  13. three two one
  14. a NaN -1.152244 0.562973
  15. d -0.252916 -0.109597 NaN
  16. c 1.273388 -0.167123 0.640382
  17. b -0.098217 0.009797 -1.299504
  18.  
  19. # DataFrame
  20. In [294]: unsorted_df.sort_index()
  21. Out[294]:
  22. three two one
  23. a NaN -1.152244 0.562973
  24. b -0.098217 0.009797 -1.299504
  25. c 1.273388 -0.167123 0.640382
  26. d -0.252916 -0.109597 NaN
  27.  
  28. In [295]: unsorted_df.sort_index(ascending=False)
  29. Out[295]:
  30. three two one
  31. d -0.252916 -0.109597 NaN
  32. c 1.273388 -0.167123 0.640382
  33. b -0.098217 0.009797 -1.299504
  34. a NaN -1.152244 0.562973
  35.  
  36. In [296]: unsorted_df.sort_index(axis=1)
  37. Out[296]:
  38. one three two
  39. a 0.562973 NaN -1.152244
  40. d NaN -0.252916 -0.109597
  41. c 0.640382 1.273388 -0.167123
  42. b -1.299504 -0.098217 0.009797
  43.  
  44. # Series
  45. In [297]: unsorted_df['three'].sort_index()
  46. Out[297]:
  47. a NaN
  48. b -0.098217
  49. c 1.273388
  50. d -0.252916
  51. Name: three, dtype: float64

By values

The Series.sort_values() method is used to sort a Series by its values. TheDataFrame.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 columnsto use to determine the sorted order.

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

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

  1. In [300]: df1[['one', 'two', 'three']].sort_values(by=['one', 'two'])
  2. Out[300]:
  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_positionargument:

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

By indexes and values

New in version 0.23.0.

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

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

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

  1. In [308]: df_multi.sort_values(by=['second', 'A'])
  2. Out[308]:
  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

Note

If a string matches both a column name and an index level name then awarning is issued and the column takes precedence. This will result in anambiguity error in a future version.

searchsorted

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

  1. In [309]: ser = pd.Series([1, 2, 3])
  2.  
  3. In [310]: ser.searchsorted([0, 3])
  4. Out[310]: array([0, 2])
  5.  
  6. In [311]: ser.searchsorted([0, 4])
  7. Out[311]: array([0, 3])
  8.  
  9. In [312]: ser.searchsorted([1, 3], side='right')
  10. Out[312]: array([1, 3])
  11.  
  12. In [313]: ser.searchsorted([1, 3], side='left')
  13. Out[313]: array([0, 2])
  14.  
  15. In [314]: ser = pd.Series([3, 1, 2])
  16.  
  17. In [315]: ser.searchsorted([0, 3], sorter=np.argsort(ser))
  18. Out[315]: array([0, 2])

smallest / largest values

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

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

DataFrame also has the nlargest and nsmallest methods.

  1. In [321]: 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.  
  6. In [322]: df.nlargest(3, 'a')
  7. Out[322]:
  8. a b c
  9. 5 11 f 3.0
  10. 3 10 c 3.2
  11. 4 8 e NaN
  12.  
  13. In [323]: df.nlargest(5, ['a', 'c'])
  14. Out[323]:
  15. a b c
  16. 5 11 f 3.0
  17. 3 10 c 3.2
  18. 4 8 e NaN
  19. 2 1 d 4.0
  20. 6 -1 f 4.0
  21.  
  22. In [324]: df.nsmallest(3, 'a')
  23. Out[324]:
  24. a b c
  25. 0 -2 a 1.0
  26. 1 -1 b 2.0
  27. 6 -1 f 4.0
  28.  
  29. In [325]: df.nsmallest(5, ['a', 'c'])
  30. Out[325]:
  31. a b c
  32. 0 -2 a 1.0
  33. 1 -1 b 2.0
  34. 6 -1 f 4.0
  35. 2 1 d 4.0
  36. 4 8 e NaN

Sorting by a MultiIndex column

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

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

Copying

The copy() method on pandas objects copies the underlying data (though notthe axis indexes, since they are immutable) and returns a new object. Note thatit is seldom necessary to copy objects. For example, there are only ahandful 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 valuesattribute 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 objectuntouched. 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 individualcolumns of a DataFrame. NumPy provides support for float,int, bool, timedelta64[ns] and datetime64[ns] (note that NumPydoes 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 thatworks with pandas. See Extension data types for a list of third-partylibraries that have implemented an extension.

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

Kind of DataData TypeScalarArrayDocumentation
tz-aware datetimeDatetimeTZDtypeTimestamparrays.DatetimeArrayTime zone handling
CategoricalCategoricalDtype(none)CategoricalCategorical data
period (time spans)PeriodDtypePeriodarrays.PeriodArrayTime span representation
sparseSparseDtype(none)arrays.SparseArraySparse data structures
intervalsIntervalDtypeIntervalarrays.IntervalArrayIntervalIndex
nullable integerInt64Dtype, …(none)arrays.IntegerArrayNullable integer data type

Pandas uses the object dtype for storing strings.

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

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

  1. In [328]: 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.  
  10. In [329]: dft
  11. Out[329]:
  12. A B C D E F G
  13. 0 0.035962 1 foo 2001-01-02 1.0 False 1
  14. 1 0.701379 1 foo 2001-01-02 1.0 False 1
  15. 2 0.281885 1 foo 2001-01-02 1.0 False 1
  16.  
  17. In [330]: dft.dtypes
  18. Out[330]:
  19. A float64
  20. B int64
  21. C object
  22. D datetime64[ns]
  23. E float32
  24. F bool
  25. G int8
  26. dtype: object

On a Series object, use the dtype attribute.

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

If a pandas object contains data with multiple dtypes in a single column, thedtype 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 [332]: pd.Series([1, 2, 3, 4, 5, 6.])
  3. Out[332]:
  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.  
  12. # string data forces an ``object`` dtype
  13. In [333]: pd.Series([1, 2, 3, 6., 'foo'])
  14. Out[333]:
  15. 0 1
  16. 1 2
  17. 2 3
  18. 3 6
  19. 4 foo
  20. dtype: object

The number of columns of each type in a DataFrame can be found by callingDataFrame.dtypes.value_counts().

  1. In [334]: dft.dtypes.value_counts()
  2. Out[334]:
  3. float32 1
  4. datetime64[ns] 1
  5. float64 1
  6. object 1
  7. bool 1
  8. int64 1
  9. int8 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. In [335]: df1 = pd.DataFrame(np.random.randn(8, 1), columns=['A'], dtype='float32')
  2.  
  3. In [336]: df1
  4. Out[336]:
  5. A
  6. 0 0.224364
  7. 1 1.890546
  8. 2 0.182879
  9. 3 0.787847
  10. 4 -0.188449
  11. 5 0.667715
  12. 6 -0.011736
  13. 7 -0.399073
  14.  
  15. In [337]: df1.dtypes
  16. Out[337]:
  17. A float32
  18. dtype: object
  19.  
  20. In [338]: df2 = pd.DataFrame({'A': pd.Series(np.random.randn(8), dtype='float16'),
  21. .....: 'B': pd.Series(np.random.randn(8)),
  22. .....: 'C': pd.Series(np.array(np.random.randn(8),
  23. .....: dtype='uint8'))})
  24. .....:
  25.  
  26. In [339]: df2
  27. Out[339]:
  28. A B C
  29. 0 0.823242 0.256090 0
  30. 1 1.607422 1.426469 0
  31. 2 -0.333740 -0.416203 255
  32. 3 -0.063477 1.139976 0
  33. 4 -1.014648 -1.193477 0
  34. 5 0.678711 0.096706 0
  35. 6 -0.040863 -1.956850 1
  36. 7 -0.357422 -0.714337 0
  37.  
  38. In [340]: df2.dtypes
  39. Out[340]:
  40. A float16
  41. B float64
  42. C uint8
  43. 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 [341]: pd.DataFrame([1, 2], columns=['a']).dtypes
  2. Out[341]:
  3. a int64
  4. dtype: object
  5.  
  6. In [342]: pd.DataFrame({'a': [1, 2]}).dtypes
  7. Out[342]:
  8. a int64
  9. dtype: object
  10.  
  11. In [343]: pd.DataFrame({'a': 1}, index=list(range(2))).dtypes
  12. Out[343]:
  13. a int64
  14. 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 [344]: frame = pd.DataFrame(np.array([1, 2]))

upcasting

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

  1. In [345]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2
  2.  
  3. In [346]: df3
  4. Out[346]:
  5. A B C
  6. 0 1.047606 0.256090 0.0
  7. 1 3.497968 1.426469 0.0
  8. 2 -0.150862 -0.416203 255.0
  9. 3 0.724370 1.139976 0.0
  10. 4 -1.203098 -1.193477 0.0
  11. 5 1.346426 0.096706 0.0
  12. 6 -0.052599 -1.956850 1.0
  13. 7 -0.756495 -0.714337 0.0
  14.  
  15. In [347]: df3.dtypes
  16. Out[347]:
  17. A float32
  18. B float64
  19. C float64
  20. dtype: object

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

  1. In [348]: df3.to_numpy().dtype
  2. Out[348]: 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 anexception 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 [349]: df3
  2. Out[349]:
  3. A B C
  4. 0 1.047606 0.256090 0.0
  5. 1 3.497968 1.426469 0.0
  6. 2 -0.150862 -0.416203 255.0
  7. 3 0.724370 1.139976 0.0
  8. 4 -1.203098 -1.193477 0.0
  9. 5 1.346426 0.096706 0.0
  10. 6 -0.052599 -1.956850 1.0
  11. 7 -0.756495 -0.714337 0.0
  12.  
  13. In [350]: df3.dtypes
  14. Out[350]:
  15. A float32
  16. B float64
  17. C float64
  18. dtype: object
  19.  
  20. # conversion of dtypes
  21. In [351]: df3.astype('float32').dtypes
  22. Out[351]:
  23. A float32
  24. B float32
  25. C float32
  26. dtype: object

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

  1. In [352]: dft = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
  2.  
  3. In [353]: dft[['a', 'b']] = dft[['a', 'b']].astype(np.uint8)
  4.  
  5. In [354]: dft
  6. Out[354]:
  7. a b c
  8. 0 1 4 7
  9. 1 2 5 8
  10. 2 3 6 9
  11.  
  12. In [355]: dft.dtypes
  13. Out[355]:
  14. a uint8
  15. b uint8
  16. c int64
  17. dtype: object

New in version 0.19.0.

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

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

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 [360]: dft = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})
  2.  
  3. In [361]: dft.loc[:, ['a', 'b']].astype(np.uint8).dtypes
  4. Out[361]:
  5. a uint8
  6. b uint8
  7. dtype: object
  8.  
  9. In [362]: dft.loc[:, ['a', 'b']] = dft.loc[:, ['a', 'b']].astype(np.uint8)
  10.  
  11. In [363]: dft.dtypes
  12. Out[363]:
  13. a int64
  14. b int64
  15. c int64
  16. 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, theDataFrame.infer_objects() and Series.infer_objects() methods can be used to soft convertto the correct type.

  1. In [364]: import datetimeIn [365]: df = pd.DataFrame([[1, 2], …..: ['a', 'b'], …..: [datetime.datetime(2016, 3, 2), …..: datetime.datetime(2016, 3, 2)]]) …..:In [366]: df = df.TIn [367]: dfOut[367]: 0 1 20 1 a 2016-03-021 2 b 2016-03-02In [368]: df.dtypesOut[368]:0 object1 object2 datetime64[ns]dtype: object

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

  1. In [369]: df.infer_objects().dtypesOut[369]:0 int641 object2 datetime64[ns]dtype: object

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

  1. In [370]: m = ['1.1', 2, 3]
  2.  
  3. In [371]: pd.to_numeric(m)
  4. Out[371]: array([1.1, 2. , 3. ])
  1. In [372]: import datetime
  2.  
  3. In [373]: m = ['2016-07-09', datetime.datetime(2016, 3, 2)]
  4.  
  5. In [374]: pd.to_datetime(m)
  6. Out[374]: DatetimeIndex(['2016-07-09', '2016-03-02'], dtype='datetime64[ns]', freq=None)
  1. In [375]: m = ['5us', pd.Timedelta('1day')]
  2.  
  3. In [376]: pd.to_timedelta(m)
  4. Out[376]: 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 elementsthat cannot be converted to desired dtype or object. By default, errors='raise', meaning that any errors encounteredwill be raised during the conversion process. However, if errors='coerce', these errors will be ignored and pandaswill convert problematic elements to pd.NaT (for datetime and timedelta) or np.nan (for numeric). This might beuseful if you are reading in data which is mostly of the desired dtype (e.g. numeric, datetime), but occasionally hasnon-conforming elements intermixed that you want to represent as missing:

  1. In [377]: import datetime
  2.  
  3. In [378]: m = ['apple', datetime.datetime(2016, 3, 2)]
  4.  
  5. In [379]: pd.to_datetime(m, errors='coerce')
  6. Out[379]: DatetimeIndex(['NaT', '2016-03-02'], dtype='datetime64[ns]', freq=None)
  7.  
  8. In [380]: m = ['apple', 2, 3]
  9.  
  10. In [381]: pd.to_numeric(m, errors='coerce')
  11. Out[381]: array([nan, 2., 3.])
  12.  
  13. In [382]: m = ['apple', pd.Timedelta('1day')]
  14.  
  15. In [383]: pd.to_timedelta(m, errors='coerce')
  16. Out[383]: 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 itencounters any errors with the conversion to a desired data type:

  1. In [384]: import datetime
  2.  
  3. In [385]: m = ['apple', datetime.datetime(2016, 3, 2)]
  4.  
  5. In [386]: pd.to_datetime(m, errors='ignore')
  6. Out[386]: Index(['apple', 2016-03-02 00:00:00], dtype='object')
  7.  
  8. In [387]: m = ['apple', 2, 3]
  9.  
  10. In [388]: pd.to_numeric(m, errors='ignore')
  11. Out[388]: array(['apple', 2, 3], dtype=object)
  12.  
  13. In [389]: m = ['apple', pd.Timedelta('1day')]
  14.  
  15. In [390]: pd.to_timedelta(m, errors='ignore')
  16. Out[390]: array(['apple', Timedelta('1 days 00:00:00')], dtype=object)

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

  1. In [391]: m = ['1', 2, 3]
  2.  
  3. In [392]: pd.to_numeric(m, downcast='integer') # smallest signed int dtype
  4. Out[392]: array([1, 2, 3], dtype=int8)
  5.  
  6. In [393]: pd.to_numeric(m, downcast='signed') # same as 'integer'
  7. Out[393]: array([1, 2, 3], dtype=int8)
  8.  
  9. In [394]: pd.to_numeric(m, downcast='unsigned') # smallest unsigned int dtype
  10. Out[394]: array([1, 2, 3], dtype=uint8)
  11.  
  12. In [395]: pd.to_numeric(m, downcast='float') # smallest float dtype
  13. Out[395]: 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 suchas DataFrames. However, with apply(), we can “apply” the function over each column efficiently:

  1. In [396]: import datetime
  2.  
  3. In [397]: df = pd.DataFrame([
  4. .....: ['2016-07-09', datetime.datetime(2016, 3, 2)]] * 2, dtype='O')
  5. .....:
  6.  
  7. In [398]: df
  8. Out[398]:
  9. 0 1
  10. 0 2016-07-09 2016-03-02 00:00:00
  11. 1 2016-07-09 2016-03-02 00:00:00
  12.  
  13. In [399]: df.apply(pd.to_datetime)
  14. Out[399]:
  15. 0 1
  16. 0 2016-07-09 2016-03-02
  17. 1 2016-07-09 2016-03-02
  18.  
  19. In [400]: df = pd.DataFrame([['1.1', 2, 3]] * 2, dtype='O')
  20.  
  21. In [401]: df
  22. Out[401]:
  23. 0 1 2
  24. 0 1.1 2 3
  25. 1 1.1 2 3
  26.  
  27. In [402]: df.apply(pd.to_numeric)
  28. Out[402]:
  29. 0 1 2
  30. 0 1.1 2 3
  31. 1 1.1 2 3
  32.  
  33. In [403]: df = pd.DataFrame([['5us', pd.Timedelta('1day')]] * 2, dtype='O')
  34.  
  35. In [404]: df
  36. Out[404]:
  37. 0 1
  38. 0 5us 1 days 00:00:00
  39. 1 5us 1 days 00:00:00
  40.  
  41. In [405]: df.apply(pd.to_timedelta)
  42. Out[405]:
  43. 0 1
  44. 0 00:00:00.000005 1 days
  45. 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 [406]: dfi = df3.astype('int32')
  2.  
  3. In [407]: dfi['E'] = 1
  4.  
  5. In [408]: dfi
  6. Out[408]:
  7. A B C E
  8. 0 1 0 0 1
  9. 1 3 1 0 1
  10. 2 0 0 255 1
  11. 3 0 1 0 1
  12. 4 -1 -1 0 1
  13. 5 1 0 0 1
  14. 6 0 -1 1 1
  15. 7 0 0 0 1
  16.  
  17. In [409]: dfi.dtypes
  18. Out[409]:
  19. A int32
  20. B int32
  21. C int32
  22. E int64
  23. dtype: object
  24.  
  25. In [410]: casted = dfi[dfi > 0]
  26.  
  27. In [411]: casted
  28. Out[411]:
  29. A B C E
  30. 0 1.0 NaN NaN 1
  31. 1 3.0 1.0 NaN 1
  32. 2 NaN NaN 255.0 1
  33. 3 NaN 1.0 NaN 1
  34. 4 NaN NaN NaN 1
  35. 5 1.0 NaN NaN 1
  36. 6 NaN NaN 1.0 1
  37. 7 NaN NaN NaN 1
  38.  
  39. In [412]: casted.dtypes
  40. Out[412]:
  41. A float64
  42. B float64
  43. C float64
  44. E int64
  45. dtype: object

While float dtypes are unchanged.

  1. In [413]: dfa = df3.copy()
  2.  
  3. In [414]: dfa['A'] = dfa['A'].astype('float32')
  4.  
  5. In [415]: dfa.dtypes
  6. Out[415]:
  7. A float32
  8. B float64
  9. C float64
  10. dtype: object
  11.  
  12. In [416]: casted = dfa[df2 > 0]
  13.  
  14. In [417]: casted
  15. Out[417]:
  16. A B C
  17. 0 1.047606 0.256090 NaN
  18. 1 3.497968 1.426469 NaN
  19. 2 NaN NaN 255.0
  20. 3 NaN 1.139976 NaN
  21. 4 NaN NaN NaN
  22. 5 1.346426 0.096706 NaN
  23. 6 NaN NaN 1.0
  24. 7 NaN NaN NaN
  25.  
  26. In [418]: casted.dtypes
  27. Out[418]:
  28. A float32
  29. B float64
  30. C float64
  31. dtype: object

Selecting columns based on dtype

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

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

  1. In [419]: 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.  
  11. In [420]: df['tdeltas'] = df.dates.diff()
  12.  
  13. In [421]: df['uint64'] = np.arange(3, 6).astype('u8')
  14.  
  15. In [422]: df['other_dates'] = pd.date_range('20130101', periods=3)
  16.  
  17. In [423]: df['tz_aware_dates'] = pd.date_range('20130101', periods=3, tz='US/Eastern')
  18.  
  19. In [424]: df
  20. Out[424]:
  21. string int64 uint8 float64 bool1 bool2 dates category tdeltas uint64 other_dates tz_aware_dates
  22. 0 a 1 3 4.0 True False 2019-11-09 19:46:31.795690 A NaT 3 2013-01-01 2013-01-01 00:00:00-05:00
  23. 1 b 2 4 5.0 False True 2019-11-10 19:46:31.795690 B 1 days 4 2013-01-02 2013-01-02 00:00:00-05:00
  24. 2 c 3 5 6.0 True False 2019-11-11 19:46:31.795690 C 1 days 5 2013-01-03 2013-01-03 00:00:00-05:00

And the dtypes:

  1. In [425]: df.dtypes
  2. Out[425]:
  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 tosay “give me the columns with these dtypes” (include) and/or “give thecolumns without these dtypes” (exclude).

For example, to select bool columns:

  1. In [426]: df.select_dtypes(include=[bool])
  2. Out[426]:
  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 [427]: df.select_dtypes(include=['bool'])
  2. Out[427]:
  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 unsignedintegers:

  1. In [428]: df.select_dtypes(include=['number', 'bool'], exclude=['unsignedinteger'])
  2. Out[428]:
  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 [429]: df.select_dtypes(include=['object'])
  2. Out[429]:
  3. string
  4. 0 a
  5. 1 b
  6. 2 c

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

  1. In [430]: 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 [431]: subdtypes(np.generic)
  2. Out[431]:
  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_]]

Note

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