Essential Basic Functionality
Here we discuss a lot of the essential functionality common to the pandas data structures. Here’s how to create some of the objects used in the examples from the previous section:
In [1]: index = pd.date_range('1/1/2000', periods=8)In [2]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])In [3]: df = pd.DataFrame(np.random.randn(8, 3), index=index,...: columns=['A', 'B', 'C'])...:In [4]: wp = pd.Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'],...: major_axis=pd.date_range('1/1/2000', periods=5),...: minor_axis=['A', 'B', 'C', 'D'])...:
Head and Tail
To view a small sample of a Series or DataFrame object, use the head() and tail() methods. The default number of elements to display is five, but you may pass a custom number.
In [5]: long_series = pd.Series(np.random.randn(1000))In [6]: long_series.head()Out[6]:0 -2.2113721 0.9744662 -2.0067473 -0.4100014 -0.078638dtype: float64In [7]: long_series.tail(3)Out[7]:997 -0.196166998 0.380733999 -0.275874dtype: float64
Attributes and Underlying Data
pandas objects have a number of attributes enabling you to access the metadata
- shape: gives the axis dimensions of the object, consistent with ndarray
- Axis labels
- Series: index (only axis)
- DataFrame: index (rows) and columns
- Panel: items, major_axis, and minor_axis
Note, these attributes can be safely assigned to!
In [8]: df[:2]Out[8]:A B C2000-01-01 -0.173215 0.119209 -1.0442362000-01-02 -0.861849 -2.104569 -0.494929In [9]: df.columns = [x.lower() for x in df.columns]In [10]: dfOut[10]:a b c2000-01-01 -0.173215 0.119209 -1.0442362000-01-02 -0.861849 -2.104569 -0.4949292000-01-03 1.071804 0.721555 -0.7067712000-01-04 -1.039575 0.271860 -0.4249722000-01-05 0.567020 0.276232 -1.0874012000-01-06 -0.673690 0.113648 -1.4784272000-01-07 0.524988 0.404705 0.5770462000-01-08 -1.715002 -1.039268 -0.370647
Pandas objects (Index, Series, DataFrame) can be thought of as containers for arrays, which hold the actual data and do the actual computation. For many types, the underlying array is a numpy.ndarray. However, pandas and 3rd party libraries may extend NumPy’s type system to add support for custom arrays (see dtypes).
To get the actual data inside a Index or Series, use the .array property
In [11]: s.arrayOut[11]:<PandasArray>[ 0.46911229990718628, -0.28286334432866328, -1.5090585031735124,-1.1356323710171934, 1.2121120250208506]Length: 5, dtype: float64In [12]: s.index.arrayOut[12]:<PandasArray>['a', 'b', 'c', 'd', 'e']Length: 5, dtype: object
array will always be an ExtensionArray. The exact details of what an ExtensionArray is and why pandas uses them is a bit beyond the scope of this introduction. See dtypes for more.
If you know you need a NumPy array, use to_numpy() or numpy.asarray().
In [13]: s.to_numpy()Out[13]: array([ 0.4691, -0.2829, -1.5091, -1.1356, 1.2121])In [14]: np.asarray(s)Out[14]: array([ 0.4691, -0.2829, -1.5091, -1.1356, 1.2121])
When the Series or Index is backed by an ExtensionArray, to_numpy() may involve copying data and coercing values. See dtypes for more.
to_numpy() gives some control over the dtype of the resulting numpy.ndarray. For example, consider datetimes with timezones. NumPy doesn’t have a dtype to represent timezone-aware datetimes, so there are two possibly useful representations:
- An object-dtype numpy.ndarray with Timestamp objects, each with the correct tz
- A
datetime64[ns]-dtype numpy.ndarray, where the values have been converted to UTC and the timezone discarded
Timezones may be preserved with dtype=object
In [15]: ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))In [16]: ser.to_numpy(dtype=object)Out[16]:array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')], dtype=object)
Or thrown away with dtype='datetime64[ns]'
In [17]: ser.to_numpy(dtype="datetime64[ns]")Out[17]: array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00.000000000'], dtype='datetime64[ns]')
Getting the “raw data” inside a DataFrame is possibly a bit more complex. When your DataFrame only has a single data type for all the columns, DataFrame.to_numpy() will return the underlying data:
In [18]: df.to_numpy()Out[18]:array([[-0.1732, 0.1192, -1.0442],[-0.8618, -2.1046, -0.4949],[ 1.0718, 0.7216, -0.7068],[-1.0396, 0.2719, -0.425 ],[ 0.567 , 0.2762, -1.0874],[-0.6737, 0.1136, -1.4784],[ 0.525 , 0.4047, 0.577 ],[-1.715 , -1.0393, -0.3706]])
If a DataFrame or Panel contains homogeneously-typed data, the ndarray can actually be modified in-place, and the changes will be reflected in the data structure. For heterogeneous data (e.g. some of the DataFrame’s columns are not all the same dtype), this will not be the case. The values attribute itself, unlike the axis labels, cannot be assigned to.
::: tip Note When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to accommodate all of the data involved. For example, if strings are involved, the result will be of object dtype. If there are only floats and integers, the resulting array will be of float dtype. :::
In the past, pandas recommended Series.values or DataFrame.values for extracting the data from a Series or DataFrame. You’ll still find references to these in old code bases and online. Going forward, we recommend avoiding .values and using .array or .to_numpy(). .values has the following drawbacks:
- When your Series contains an extension type, it’s unclear whether Series.values returns a NumPy array or the extension array. Series.array will always return an ExtensionArray, and will never copy data. Series.to_numpy() will always return a NumPy array, potentially at the cost of copying / coercing values.
- When your DataFrame contains a mixture of data types, DataFrame.values may involve copying data and coercing values to a common dtype, a relatively expensive operation. DataFrame.to_numpy(), being a method, makes it clearer that the returned NumPy array may not be a view on the same data in the DataFrame.
Accelerated operations
pandas has support for accelerating certain types of binary numerical and boolean operations using the numexpr library and the bottleneck libraries.
These libraries are especially useful when dealing with large data sets, and provide large speedups. numexpr uses smart chunking, caching, and multiple cores. bottleneck is a set of specialized cython routines that are especially fast when dealing with arrays that have nans.
Here is a sample (using 100 column x 100,000 row DataFrames):
| Operation | 0.11.0 (ms) | Prior Version (ms) | Ratio to Prior |
|---|---|---|---|
| df1 > df2 | 13.32 | 125.35 | 0.1063 |
| df1 * df2 | 21.71 | 36.63 | 0.5928 |
| df1 + df2 | 22.04 | 36.50 | 0.6039 |
You are highly encouraged to install both libraries. See the section Recommended Dependencies for more installation info.
These are both enabled to be used by default, you can control this by setting the options:
New in version 0.20.0.
pd.set_option('compute.use_bottleneck', False)pd.set_option('compute.use_numexpr', False)
Flexible binary operations
With binary operations between pandas data structures, there are two key points of interest:
- Broadcasting behavior between higher- (e.g. DataFrame) and lower-dimensional (e.g. Series) objects.
- Missing data in computations.
We will demonstrate how to manage these issues independently, though they can be handled simultaneously.
Matching / broadcasting behavior
DataFrame has the methods add(), sub(), mul(), div() and related functions radd(), rsub(), … for carrying out binary operations. For broadcasting behavior, Series input is of primary interest. Using these functions, you can use to either match on the index or columns via the axis keyword:
In [19]: df = pd.DataFrame({....: 'one': pd.Series(np.random.randn(3), index=['a', 'b', 'c']),....: 'two': pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),....: 'three': pd.Series(np.random.randn(3), index=['b', 'c', 'd'])})....:In [20]: dfOut[20]:one two threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [21]: row = df.iloc[1]In [22]: column = df['two']In [23]: df.sub(row, axis='columns')Out[23]:one two threea 1.757280 -2.688953 NaNb 0.000000 0.000000 0.000000c 1.153738 -0.121396 -0.402113d NaN 0.507782 -2.065853In [24]: df.sub(row, axis=1)Out[24]:one two threea 1.757280 -2.688953 NaNb 0.000000 0.000000 0.000000c 1.153738 -0.121396 -0.402113d NaN 0.507782 -2.065853In [25]: df.sub(column, axis='index')Out[25]:one two threea 3.043851 0.0 NaNb -1.402381 0.0 -0.650888c -0.127247 0.0 -0.931605d NaN 0.0 -3.224524In [26]: df.sub(column, axis=0)Out[26]:one two threea 3.043851 0.0 NaNb -1.402381 0.0 -0.650888c -0.127247 0.0 -0.931605d NaN 0.0 -3.224524
Furthermore you can align a level of a MultiIndexed DataFrame with a Series.
In [27]: dfmi = df.copy()In [28]: dfmi.index = pd.MultiIndex.from_tuples([(1, 'a'), (1, 'b'),....: (1, 'c'), (2, 'a')],....: names=['first', 'second'])....:In [29]: dfmi.sub(column, axis=0, level='second')Out[29]:one two threefirst second1 a 3.043851 0.000000 NaNb -1.402381 0.000000 -0.650888c -0.127247 0.000000 -0.9316052 a NaN 3.196734 -0.027789
With Panel, describing the matching behavior is a bit more difficult, so the arithmetic methods instead (and perhaps confusingly?) give you the option to specify the broadcast axis. For example, suppose we wished to demean the data over a particular axis. This can be accomplished by taking the mean over an axis and broadcasting over the same axis:
In [30]: major_mean = wp.mean(axis='major')In [31]: major_meanOut[31]:Item1 Item2A -0.378069 0.675929B -0.241429 -0.018080C -0.597702 0.129006D 0.204005 0.245570In [32]: wp.sub(major_mean, axis='major')Out[32]:<class 'pandas.core.panel.Panel'>Dimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)Items axis: Item1 to Item2Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00Minor_axis axis: A to D
And similarly for axis="items" and axis="minor".
::: tip Note I could be convinced to make the axis argument in the DataFrame methods match the broadcasting behavior of Panel. Though it would require a transition period so users can change their code… :::
Series and Index also support the divmod() builtin. This function takes the floor division and modulo operation at the same time returning a two-tuple of the same type as the left hand side. For example:
In [33]: s = pd.Series(np.arange(10))In [34]: sOut[34]:0 01 12 23 34 45 56 67 78 89 9dtype: int64In [35]: div, rem = divmod(s, 3)In [36]: divOut[36]:0 01 02 03 14 15 16 27 28 29 3dtype: int64In [37]: remOut[37]:0 01 12 23 04 15 26 07 18 29 0dtype: int64In [38]: idx = pd.Index(np.arange(10))In [39]: idxOut[39]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')In [40]: div, rem = divmod(idx, 3)In [41]: divOut[41]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2, 3], dtype='int64')In [42]: remOut[42]: Int64Index([0, 1, 2, 0, 1, 2, 0, 1, 2, 0], dtype='int64')We can also do elementwise divmod():In [43]: div, rem = divmod(s, [2, 2, 3, 3, 4, 4, 5, 5, 6, 6])In [44]: divOut[44]:0 01 02 03 14 15 16 17 18 19 1dtype: int64In [45]: remOut[45]:0 01 12 23 04 05 16 17 28 29 3dtype: int64
Missing data / operations with fill values
In Series and DataFrame, the arithmetic functions have the option of inputting a fill_value, namely a value to substitute when at most one of the values at a location are missing. For example, when adding two DataFrame objects, you may wish to treat NaN as 0 unless both DataFrames are missing that value, in which case the result will be NaN (you can later replace NaN with some other value using fillna if you wish).
In [46]: dfOut[46]:one two threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [47]: df2Out[47]:one two threea 1.400810 -1.643041 1.000000b -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [48]: df + df2Out[48]:one two threea 2.801620 -3.286083 NaNb -0.712940 2.091822 0.790046c 1.594536 1.849030 -0.014180d NaN 3.107386 -3.341661In [49]: df.add(df2, fill_value=0)Out[49]:one two threea 2.801620 -3.286083 1.000000b -0.712940 2.091822 0.790046c 1.594536 1.849030 -0.014180d NaN 3.107386 -3.341661
Flexible Comparisons
Series and DataFrame have the binary comparison methods eq, ne, lt, gt, le, and ge whose behavior is analogous to the binary arithmetic operations described above:
In [50]: df.gt(df2)Out[50]:one two threea False False Falseb False False Falsec False False Falsed False False FalseIn [51]: df2.ne(df)Out[51]:one two threea False False Trueb False False Falsec False False Falsed True False False
These operations produce a pandas object of the same type as the left-hand-side input that is of dtype bool. These boolean objects can be used in indexing operations, see the section on Boolean indexing.
Boolean Reductions
You can apply the reductions: empty, any(), all(), and bool() to provide a way to summarize a boolean result.
In [52]: (df > 0).all()Out[52]:one Falsetwo Falsethree Falsedtype: boolIn [53]: (df > 0).any()Out[53]:one Truetwo Truethree Truedtype: bool
You can reduce to a final boolean value.
In [54]: (df > 0).any().any()Out[54]: True
You can test if a pandas object is empty, via the empty property.
In [55]: df.emptyOut[55]: FalseIn [56]: pd.DataFrame(columns=list('ABC')).emptyOut[56]: True
To evaluate single-element pandas objects in a boolean context, use the method bool():
In [57]: pd.Series([True]).bool()Out[57]: TrueIn [58]: pd.Series([False]).bool()Out[58]: FalseIn [59]: pd.DataFrame([[True]]).bool()Out[59]: TrueIn [60]: pd.DataFrame([[False]]).bool()Out[60]: False
::: Warning Warning
You might be tempted to do the following:
>>> if df:... pass
Or
>>> df and df2
These will both raise errors, as you are trying to compare multiple values.:
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
:::
See gotchas for a more detailed discussion.
Comparing if objects are equivalent
Often you may find that there is more than one way to compute the same result. As a simple example, consider df + df and df * 2. To test that these two computations produce the same result, given the tools shown above, you might imagine using (df + df == df * 2).all(). But in fact, this expression is False:
In [61]: df + df == df * 2Out[61]:one two threea True True Falseb True True Truec True True Trued False True TrueIn [62]: (df + df == df * 2).all()Out[62]:one Falsetwo Truethree Falsedtype: bool
Notice that the boolean DataFrame df + df == df * 2 contains some False values! This is because NaNs do not compare as equals:
In [63]: np.nan == np.nanOut[63]: False
So, NDFrames (such as Series, DataFrames, and Panels) have an equals() method for testing equality, with NaNs in corresponding locations treated as equal.
In [64]: (df + df).equals(df * 2)Out[64]: True
Note that the Series or DataFrame index needs to be in the same order for equality to be True:
In [65]: df1 = pd.DataFrame({'col': ['foo', 0, np.nan]})In [66]: df2 = pd.DataFrame({'col': [np.nan, 0, 'foo']}, index=[2, 1, 0])In [67]: df1.equals(df2)Out[67]: FalseIn [68]: df1.equals(df2.sort_index())Out[68]: True
Comparing array-like objects
You can conveniently perform element-wise comparisons when comparing a pandas data structure with a scalar value:
In [69]: pd.Series(['foo', 'bar', 'baz']) == 'foo'Out[69]:0 True1 False2 Falsedtype: boolIn [70]: pd.Index(['foo', 'bar', 'baz']) == 'foo'Out[70]: array([ True, False, False], dtype=bool)
Pandas also handles element-wise comparisons between different array-like objects of the same length:
In [71]: pd.Series(['foo', 'bar', 'baz']) == pd.Index(['foo', 'bar', 'qux'])Out[71]:0 True1 True2 Falsedtype: boolIn [72]: pd.Series(['foo', 'bar', 'baz']) == np.array(['foo', 'bar', 'qux'])Out[72]:0 True1 True2 Falsedtype: bool
Trying to compare Index or Series objects of different lengths will raise a ValueError:
In [55]: pd.Series(['foo', 'bar', 'baz']) == pd.Series(['foo', 'bar'])ValueError: Series lengths must match to compareIn [56]: pd.Series(['foo', 'bar', 'baz']) == pd.Series(['foo'])ValueError: Series lengths must match to compare
Note that this is different from the NumPy behavior where a comparison can be broadcast:
In [73]: np.array([1, 2, 3]) == np.array([2])Out[73]: array([False, True, False], dtype=bool)
or it can return False if broadcasting can not be done:
In [74]: np.array([1, 2, 3]) == np.array([1, 2])Out[74]: False
Combining overlapping data sets
A problem occasionally arising is the combination of two similar data sets where values in one are preferred over the other. An example would be two data series representing a particular economic indicator where one is considered to be of “higher quality”. However, the lower quality series might extend further back in history or have more complete data coverage. As such, we would like to combine two DataFrame objects where missing values in one DataFrame are conditionally filled with like-labeled values from the other DataFrame. The function implementing this operation is combine_first(), which we illustrate:
In [75]: df1 = pd.DataFrame({'A': [1., np.nan, 3., 5., np.nan],....: 'B': [np.nan, 2., 3., np.nan, 6.]})....:In [76]: df2 = pd.DataFrame({'A': [5., 2., 4., np.nan, 3., 7.],....: 'B': [np.nan, np.nan, 3., 4., 6., 8.]})....:In [77]: df1Out[77]:A B0 1.0 NaN1 NaN 2.02 3.0 3.03 5.0 NaN4 NaN 6.0In [78]: df2Out[78]:A B0 5.0 NaN1 2.0 NaN2 4.0 3.03 NaN 4.04 3.0 6.05 7.0 8.0In [79]: df1.combine_first(df2)Out[79]:A B0 1.0 NaN1 2.0 2.02 3.0 3.03 5.0 4.04 3.0 6.05 7.0 8.0
General DataFrame Combine
The combine_first() method above calls the more general DataFrame.combine(). This method takes another DataFrame and a combiner function, aligns the input DataFrame and then passes the combiner function pairs of Series (i.e., columns whose names are the same).
So, for instance, to reproduce combine_first() as above:
In [80]: def combiner(x, y):....: return np.where(pd.isna(x), y, x)....:
Descriptive statistics
There exists a large number of methods for computing descriptive statistics and other related operations on Series, DataFrame, and Panel. Most of these are aggregations (hence producing a lower-dimensional result) like sum(), mean(), and quantile(), but some of them, like cumsum() and cumprod(), produce an object of the same size. Generally speaking, these methods take an axis argument, just like ndarray .{sum, std, …}, but the axis can be specified by name or integer:
- Series: no axis argument needed
- DataFrame: “index” (axis=0, default), “columns” (axis=1)
- Panel: “items” (axis=0), “major” (axis=1, default), “minor” (axis=2)
For example:
In [81]: dfOut[81]:one two threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [82]: df.mean(0)Out[82]:one 0.613869two 0.470270three -0.427633dtype: float64In [83]: df.mean(1)Out[83]:a -0.121116b 0.361488c 0.571564d -0.058569dtype: float64
All such methods have a skipna option signaling whether to exclude missing data (True by default):
In [84]: df.sum(0, skipna=False)Out[84]:one NaNtwo 1.881078three NaNdtype: float64In [85]: df.sum(axis=1, skipna=True)Out[85]:a -0.242232b 1.084464c 1.714693d -0.117137dtype: float64
Combined with the broadcasting / arithmetic behavior, one can describe various statistical procedures, like standardization (rendering data zero mean and standard deviation 1), very concisely:
In [86]: ts_stand = (df - df.mean()) / df.std()In [87]: ts_stand.std()Out[87]:one 1.0two 1.0three 1.0dtype: float64In [88]: xs_stand = df.sub(df.mean(1), axis=0).div(df.std(1), axis=0)In [89]: xs_stand.std(1)Out[89]:a 1.0b 1.0c 1.0d 1.0dtype: float64
Note that methods like cumsum() and cumprod() preserve the location of NaN values. This is somewhat different from expanding() and rolling(). For more details please see this note.
In [90]: df.cumsum()Out[90]:one two threea 1.400810 -1.643041 NaNb 1.044340 -0.597130 0.395023c 1.841608 0.327385 0.387933d NaN 1.881078 -1.282898
Here is a quick reference summary table of common functions. Each also takes an optional level parameter which applies only if the object has a hierarchical index.
| Function | Description |
|---|---|
| count | Number of non-NA observations |
| sum | Sum of values |
| mean | Mean of values |
| mad | Mean absolute deviation |
| median | Arithmetic median of values |
| min | Minimum |
| max | Maximum |
| mode | Mode |
| abs | Absolute Value |
| prod | Product of values |
| std | Bessel-corrected sample standard deviation |
| var | Unbiased variance |
| sem | Standard error of the mean |
| skew | Sample skewness (3rd moment) |
| kurt | Sample kurtosis (4th moment) |
| quantile | Sample quantile (value at %) |
| cumsum | Cumulative sum |
| cumprod | Cumulative product |
| cummax | Cumulative maximum |
| cummin | Cumulative minimum |
Note that by chance some NumPy methods, like mean, std, and sum, will exclude NAs on Series input by default:
In [91]: np.mean(df['one'])Out[91]: 0.6138692844180106In [92]: np.mean(df['one'].to_numpy())Out[92]: nan
Series.nunique() will return the number of unique non-NA values in a Series:
In [93]: series = pd.Series(np.random.randn(500))In [94]: series[20:500] = np.nanIn [95]: series[10:20] = 5In [96]: series.nunique()Out[96]: 11
Summarizing data: describe
There is a convenient describe() function which computes a variety of summary statistics about a Series or the columns of a DataFrame (excluding NAs of course):
In [97]: series = pd.Series(np.random.randn(1000))In [98]: series[::2] = np.nanIn [99]: series.describe()Out[99]:count 500.000000mean -0.020695std 1.011840min -2.68376325% -0.70929750% -0.07021175% 0.712856max 3.160915dtype: float64In [100]: frame = pd.DataFrame(np.random.randn(1000, 5),.....: columns=['a', 'b', 'c', 'd', 'e']).....:In [101]: frame.iloc[::2] = np.nanIn [102]: frame.describe()Out[102]:a b c d ecount 500.000000 500.000000 500.000000 500.000000 500.000000mean 0.026515 0.022952 -0.047307 -0.052551 0.011210std 1.016752 0.980046 1.020837 1.008271 1.006726min -3.000951 -2.637901 -3.303099 -3.159200 -3.18882125% -0.647623 -0.593587 -0.709906 -0.691338 -0.68917650% 0.047578 -0.026675 -0.029655 -0.032769 -0.01577575% 0.723946 0.771931 0.603753 0.667044 0.652221max 2.740139 2.752332 3.004229 2.728702 3.240991
You can select specific percentiles to include in the output:
In [103]: series.describe(percentiles=[.05, .25, .75, .95])Out[103]:count 500.000000mean -0.020695std 1.011840min -2.6837635% -1.64133725% -0.70929750% -0.07021175% 0.71285695% 1.699176max 3.160915dtype: float64
By default, the median is always included.
For a non-numerical Series object, describe() will give a simple summary of the number of unique values and most frequently occurring values:
In [104]: s = pd.Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])In [105]: s.describe()Out[105]:count 9unique 4top afreq 5dtype: object
Note that on a mixed-type DataFrame object, describe() will restrict the summary to include only numerical columns or, if none are, only categorical columns:
In [106]: frame = pd.DataFrame({'a': ['Yes', 'Yes', 'No', 'No'], 'b': range(4)})In [107]: frame.describe()Out[107]:bcount 4.000000mean 1.500000std 1.290994min 0.00000025% 0.75000050% 1.50000075% 2.250000max 3.000000
This behavior can be controlled by providing a list of types as include/exclude arguments. The special value all can also be used:
In [108]: frame.describe(include=['object'])Out[108]:acount 4unique 2top Yesfreq 2In [109]: frame.describe(include=['number'])Out[109]:bcount 4.000000mean 1.500000std 1.290994min 0.00000025% 0.75000050% 1.50000075% 2.250000max 3.000000In [110]: frame.describe(include='all')Out[110]:a bcount 4 4.000000unique 2 NaNtop Yes NaNfreq 2 NaNmean NaN 1.500000std NaN 1.290994min NaN 0.00000025% NaN 0.75000050% NaN 1.50000075% NaN 2.250000max NaN 3.000000
That feature relies on select_dtypes. Refer to there for details about accepted inputs.
Index of Min/Max Values
The idxmin() and idxmax() functions on Series and DataFrame compute the index labels with the minimum and maximum corresponding values:
In [111]: s1 = pd.Series(np.random.randn(5))In [112]: s1Out[112]:0 -0.0688221 -1.1297882 -0.2697983 -0.3755804 0.513381dtype: float64In [113]: s1.idxmin(), s1.idxmax()Out[113]: (1, 4)In [114]: df1 = pd.DataFrame(np.random.randn(5, 3), columns=['A', 'B', 'C'])In [115]: df1Out[115]:A B C0 0.333329 -0.910090 -1.3212201 2.111424 1.701169 0.8583362 -0.608055 -2.082155 -0.0696183 1.412817 -0.562658 0.7700424 0.373294 -0.965381 -1.607840In [116]: df1.idxmin(axis=0)Out[116]:A 2B 2C 4dtype: int64In [117]: df1.idxmax(axis=1)Out[117]:0 A1 A2 C3 A4 Adtype: object
When there are multiple rows (or columns) matching the minimum or maximum value, idxmin() and idxmax() return the first matching index:
In [118]: df3 = pd.DataFrame([2, 1, 1, 3, np.nan], columns=['A'], index=list('edcba'))In [119]: df3Out[119]:Ae 2.0d 1.0c 1.0b 3.0a NaNIn [120]: df3['A'].idxmin()Out[120]: 'd'
::: tip Note
idxmin and idxmax are called argmin and argmax in NumPy.
:::
Value counts (histogramming) / Mode
The value_counts() Series method and top-level function computes a histogram of a 1D array of values. It can also be used as a function on regular arrays:
In [121]: data = np.random.randint(0, 7, size=50)In [122]: dataOut[122]:array([6, 4, 1, 3, 4, 4, 4, 6, 5, 2, 6, 1, 0, 4, 3, 2, 5, 3, 4, 0, 5, 3, 0,1, 5, 0, 1, 5, 3, 4, 1, 2, 3, 2, 4, 6, 1, 4, 3, 5, 2, 1, 2, 4, 1, 6,3, 6, 3, 3])In [123]: s = pd.Series(data)In [124]: s.value_counts()Out[124]:4 103 101 86 65 62 60 4dtype: int64In [125]: pd.value_counts(data)Out[125]:4 103 101 86 65 62 60 4dtype: int64
Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame:
In [126]: s5 = pd.Series([1, 1, 3, 3, 3, 5, 5, 7, 7, 7])In [127]: s5.mode()Out[127]:0 31 7dtype: int64In [128]: df5 = pd.DataFrame({"A": np.random.randint(0, 7, size=50),.....: "B": np.random.randint(-10, 15, size=50)}).....:In [129]: df5.mode()Out[129]:A B0 0 -9
Discretization and quantiling
Continuous values can be discretized using the cut() (bins based on values) and qcut() (bins based on sample quantiles) functions:
In [130]: arr = np.random.randn(20)In [131]: factor = pd.cut(arr, 4)In [132]: factorOut[132]:[(1.27, 2.31], (0.231, 1.27], (-0.809, 0.231], (-1.853, -0.809], (1.27, 2.31], ..., (0.231, 1.27], (-0.809, 0.231], (-1.853, -0.809], (1.27, 2.31], (0.231, 1.27]]Length: 20Categories (4, interval[float64]): [(-1.853, -0.809] < (-0.809, 0.231] < (0.231, 1.27] < (1.27, 2.31]]In [133]: factor = pd.cut(arr, [-5, -1, 0, 1, 5])In [134]: factorOut[134]:[(1, 5], (0, 1], (-1, 0], (-5, -1], (1, 5], ..., (1, 5], (-1, 0], (-5, -1], (1, 5], (0, 1]]Length: 20Categories (4, interval[int64]): [(-5, -1] < (-1, 0] < (0, 1] < (1, 5]]
qcut() computes sample quantiles. For example, we could slice up some normally distributed data into equal-size quartiles like so:
In [135]: arr = np.random.randn(30)In [136]: factor = pd.qcut(arr, [0, .25, .5, .75, 1])In [137]: factorOut[137]:[(-2.219, -0.669], (-0.669, 0.00453], (0.367, 2.369], (0.00453, 0.367], (0.367, 2.369], ..., (0.00453, 0.367], (0.367, 2.369], (0.00453, 0.367], (-0.669, 0.00453], (0.367, 2.369]]Length: 30Categories (4, interval[float64]): [(-2.219, -0.669] < (-0.669, 0.00453] < (0.00453, 0.367] <(0.367, 2.369]]In [138]: pd.value_counts(factor)Out[138]:(0.367, 2.369] 8(-2.219, -0.669] 8(0.00453, 0.367] 7(-0.669, 0.00453] 7dtype: int64
We can also pass infinite values to define the bins:
In [139]: arr = np.random.randn(20)In [140]: factor = pd.cut(arr, [-np.inf, 0, np.inf])In [141]: factorOut[141]:[(0.0, inf], (-inf, 0.0], (-inf, 0.0], (-inf, 0.0], (-inf, 0.0], ..., (-inf, 0.0], (-inf, 0.0], (0.0, inf], (-inf, 0.0], (-inf, 0.0]]Length: 20Categories (2, interval[float64]): [(-inf, 0.0] < (0.0, inf]]
Function application
To apply your own or another library’s functions to pandas objects, you should be aware of the three methods below. The appropriate method to use depends on whether your function expects to operate on an entire DataFrame or Series, row- or column-wise, or elementwise.
- Tablewise Function Application: pipe()
- Row or Column-wise Function Application: apply()
- Aggregation API: agg() and transform()
- Applying Elementwise Functions: applymap()
Tablewise Function Application
DataFrames and Series can of course just be passed into functions. However, if the function needs to be called in a chain, consider using the pipe() method. Compare the following
# f, g, and h are functions taking and returning ``DataFrames``>>> f(g(h(df), arg1=1), arg2=2, arg3=3)
with the equivalent
>>> (df.pipe(h)... .pipe(g, arg1=1)... .pipe(f, arg2=2, arg3=3))
Pandas encourages the second style, which is known as method chaining. pipe makes it easy to use your own or another library’s functions in method chains, alongside pandas’ methods.
In the example above, the functions f, g, and h each expected the DataFrame as the first positional argument. What if the function you wish to apply takes its data as, say, the second argument? In this case, provide pipe with a tuple of (callable, data_keyword). .pipe will route the DataFrame to the argument specified in the tuple.
For example, we can fit a regression using statsmodels. Their API expects a formula first and a DataFrame as the second argument, data. We pass in the function, keyword pair (sm.ols, 'data') to pipe:
In [142]: import statsmodels.formula.api as smIn [143]: bb = pd.read_csv('data/baseball.csv', index_col='id')In [144]: (bb.query('h > 0').....: .assign(ln_h=lambda df: np.log(df.h)).....: .pipe((sm.ols, 'data'), 'hr ~ ln_h + year + g + C(lg)').....: .fit().....: .summary().....: ).....:Out[144]:<class 'statsmodels.iolib.summary.Summary'>"""OLS Regression Results==============================================================================Dep. Variable: hr R-squared: 0.685Model: OLS Adj. R-squared: 0.665Method: Least Squares F-statistic: 34.28Date: Tue, 12 Mar 2019 Prob (F-statistic): 3.48e-15Time: 22:38:35 Log-Likelihood: -205.92No. Observations: 68 AIC: 421.8Df Residuals: 63 BIC: 432.9Df Model: 4Covariance Type: nonrobust===============================================================================coef std err t P>|t| [0.025 0.975]-------------------------------------------------------------------------------Intercept -8484.7720 4664.146 -1.819 0.074 -1.78e+04 835.780C(lg)[T.NL] -2.2736 1.325 -1.716 0.091 -4.922 0.375ln_h -1.3542 0.875 -1.547 0.127 -3.103 0.395year 4.2277 2.324 1.819 0.074 -0.417 8.872g 0.1841 0.029 6.258 0.000 0.125 0.243==============================================================================Omnibus: 10.875 Durbin-Watson: 1.999Prob(Omnibus): 0.004 Jarque-Bera (JB): 17.298Skew: 0.537 Prob(JB): 0.000175Kurtosis: 5.225 Cond. No. 1.49e+07==============================================================================Warnings:[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.[2] The condition number is large, 1.49e+07. This might indicate that there arestrong multicollinearity or other numerical problems."""
The pipe method is inspired by unix pipes and more recently dplyr and magrittr, which have introduced the popular (%>%) (read pipe) operator for R. The implementation of pipe here is quite clean and feels right at home in python. We encourage you to view the source code of pipe().
Row or Column-wise Function Application
Arbitrary functions can be applied along the axes of a DataFrame using the apply() method, which, like the descriptive statistics methods, takes an optional axis argument:
In [145]: df.apply(np.mean)Out[145]:one 0.613869two 0.470270three -0.427633dtype: float64In [146]: df.apply(np.mean, axis=1)Out[146]:a -0.121116b 0.361488c 0.571564d -0.058569dtype: float64In [147]: df.apply(lambda x: x.max() - x.min())Out[147]:one 1.757280two 3.196734three 2.065853dtype: float64In [148]: df.apply(np.cumsum)Out[148]:one two threea 1.400810 -1.643041 NaNb 1.044340 -0.597130 0.395023c 1.841608 0.327385 0.387933d NaN 1.881078 -1.282898In [149]: df.apply(np.exp)Out[149]:one two threea 4.058485 0.193391 NaNb 0.700143 2.845991 1.484418c 2.219469 2.520646 0.992935d NaN 4.728902 0.188091
The apply() method will also dispatch on a string method name.
In [150]: df.apply('mean')Out[150]:one 0.613869two 0.470270three -0.427633dtype: float64In [151]: df.apply('mean', axis=1)Out[151]:a -0.121116b 0.361488c 0.571564d -0.058569dtype: float64
The return type of the function passed to apply() affects the type of the final output from DataFrame.apply for the default behaviour:
- If the applied function returns a
Series, the final output is aDataFrame. The columns match the index of theSeriesreturned by the applied function. - If the applied function returns any other type, the final output is a
Series.
This default behaviour can be overridden using the result_type, which accepts three options: reduce, broadcast, and expand. These will determine how list-likes return values expand (or not) to a DataFrame.
apply() combined with some cleverness can be used to answer many questions about a data set. For example, suppose we wanted to extract the date where the maximum value for each column occurred:
In [152]: tsdf = pd.DataFrame(np.random.randn(1000, 3), columns=['A', 'B', 'C'],.....: index=pd.date_range('1/1/2000', periods=1000)).....:In [153]: tsdf.apply(lambda x: x.idxmax())Out[153]:A 2000-06-10B 2001-07-04C 2002-08-09dtype: datetime64[ns]
You may also pass additional arguments and keyword arguments to the apply() method. For instance, consider the following function you would like to apply:
def subtract_and_divide(x, sub, divide=1):return (x - sub) / divide
You may then apply this function as follows:
df.apply(subtract_and_divide, args=(5,), divide=3)
Another useful feature is the ability to pass Series methods to carry out some Series operation on each column or row:
In [154]: tsdfOut[154]:A B C2000-01-01 -0.652077 -0.239118 0.8412722000-01-02 0.130224 0.347505 -0.3856662000-01-03 -1.700237 -0.925899 0.1995642000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.339319 -0.978307 0.6894922000-01-09 0.601495 -0.630417 -1.0400792000-01-10 1.511723 -0.427952 -0.400154In [155]: tsdf.apply(pd.Series.interpolate)Out[155]:A B C2000-01-01 -0.652077 -0.239118 0.8412722000-01-02 0.130224 0.347505 -0.3856662000-01-03 -1.700237 -0.925899 0.1995642000-01-04 -1.292326 -0.936380 0.2975502000-01-05 -0.884415 -0.946862 0.3955352000-01-06 -0.476503 -0.957344 0.4935212000-01-07 -0.068592 -0.967825 0.5915072000-01-08 0.339319 -0.978307 0.6894922000-01-09 0.601495 -0.630417 -1.0400792000-01-10 1.511723 -0.427952 -0.400154
Finally, apply() takes an argument raw which is False by default, which converts each row or column into a Series before applying the function. When set to True, the passed function will instead receive an ndarray object, which has positive performance implications if you do not need the indexing functionality.
Aggregation API
New in version 0.20.0.
The aggregation API allows one to express possibly multiple aggregation operations in a single concise way. This API is similar across pandas objects, see groupby API, the window functions API, and the resample API. The entry point for aggregation is DataFrame.aggregate(), or the alias DataFrame.agg().
We will use a similar starting frame from above:
In [156]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],.....: index=pd.date_range('1/1/2000', periods=10)).....:In [157]: tsdf.iloc[3:7] = np.nanIn [158]: tsdfOut[158]:A B C2000-01-01 0.396575 -0.364907 0.0512902000-01-02 -0.310517 -0.369093 -0.3531512000-01-03 -0.522441 1.659115 -0.2723642000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 -0.057890 1.148901 0.0115282000-01-09 -0.155578 0.742150 0.1073242000-01-10 0.531797 0.080254 0.833297
Using a single function is equivalent to papply(). You can also pass named methods as strings. These will return a Series of the aggregated output:
In [159]: tsdf.agg(np.sum)Out[159]:A -0.118055B 2.896420C 0.377923dtype: float64In [160]: tsdf.agg('sum')Out[160]:A -0.118055B 2.896420C 0.377923dtype: float64# these are equivalent to a ``.sum()`` because we are aggregating# on a single functionIn [161]: tsdf.sum()Out[161]:A -0.118055B 2.896420C 0.377923dtype: float64
Single aggregations on a Series this will return a scalar value:
In [162]: tsdf.A.agg('sum')Out[162]: -0.11805495013260869
Aggregating with multiple functions
You can pass multiple aggregation arguments as a list. The results of each of the passed functions will be a row in the resulting DataFrame. These are naturally named from the aggregation function.
In [163]: tsdf.agg(['sum'])Out[163]:A B Csum -0.118055 2.89642 0.377923
Multiple functions yield multiple rows:
In [164]: tsdf.agg(['sum', 'mean'])Out[164]:A B Csum -0.118055 2.896420 0.377923mean -0.019676 0.482737 0.062987
On a Series, multiple functions return a Series, indexed by the function names:
In [165]: tsdf.A.agg(['sum', 'mean'])Out[165]:sum -0.118055mean -0.019676Name: A, dtype: float64
Passing a lambda function will yield a <lambda> named row:
In [166]: tsdf.A.agg(['sum', lambda x: x.mean()])Out[166]:sum -0.118055<lambda> -0.019676Name: A, dtype: float64
Passing a named function will yield that name for the row:
In [167]: def mymean(x):.....: return x.mean().....:In [168]: tsdf.A.agg(['sum', mymean])Out[168]:sum -0.118055mymean -0.019676Name: A, dtype: float64
Aggregating with a dict
Passing a dictionary of column names to a scalar or a list of scalars, to DataFrame.agg allows you to customize which functions are applied to which columns. Note that the results are not in any particular order, you can use an OrderedDict instead to guarantee ordering.
In [169]: tsdf.agg({'A': 'mean', 'B': 'sum'})Out[169]:A -0.019676B 2.896420dtype: float64
Passing a list-like will generate a DataFrame output. You will get a matrix-like output of all of the aggregators. The output will consist of all unique functions. Those that are not noted for a particular column will be NaN:
In [170]: tsdf.agg({'A': ['mean', 'min'], 'B': 'sum'})Out[170]:A Bmean -0.019676 NaNmin -0.522441 NaNsum NaN 2.89642
Mixed Dtypes
When presented with mixed dtypes that cannot aggregate, .agg will only take the valid aggregations. This is similar to how groupby .agg works.
In [171]: mdf = pd.DataFrame({'A': [1, 2, 3],.....: 'B': [1., 2., 3.],.....: 'C': ['foo', 'bar', 'baz'],.....: 'D': pd.date_range('20130101', periods=3)}).....:In [172]: mdf.dtypesOut[172]:A int64B float64C objectD datetime64[ns]dtype: object
In [173]: mdf.agg(['min', 'sum'])Out[173]:A B C Dmin 1 1.0 bar 2013-01-01sum 6 6.0 foobarbaz NaT
Custom describe
With .agg() is it possible to easily create a custom describe function, similar to the built in describe function.
In [174]: from functools import partialIn [175]: q_25 = partial(pd.Series.quantile, q=0.25)In [176]: q_25.__name__ = '25%'In [177]: q_75 = partial(pd.Series.quantile, q=0.75)In [178]: q_75.__name__ = '75%'In [179]: tsdf.agg(['count', 'mean', 'std', 'min', q_25, 'median', q_75, 'max'])Out[179]:A B Ccount 6.000000 6.000000 6.000000mean -0.019676 0.482737 0.062987std 0.408577 0.836785 0.420419min -0.522441 -0.369093 -0.35315125% -0.271782 -0.253617 -0.201391median -0.106734 0.411202 0.03140975% 0.282958 1.047213 0.093315max 0.531797 1.659115 0.833297
Transform API
New in version 0.20.0.
The transform() method returns an object that is indexed the same (same size) as the original. This API allows you to provide multiple operations at the same time rather than one-by-one. Its API is quite similar to the .agg API.
We create a frame similar to the one used in the above sections.
In [180]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],.....: index=pd.date_range('1/1/2000', periods=10)).....:In [181]: tsdf.iloc[3:7] = np.nanIn [182]: tsdfOut[182]:A B C2000-01-01 -1.219234 -1.652700 -0.6982772000-01-02 1.858653 -0.738520 0.6303642000-01-03 -0.112596 1.525897 1.3642252000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 -0.527790 -1.715506 0.3872742000-01-09 -0.569341 0.569386 0.1341362000-01-10 -0.413993 -0.862280 0.662690
Transform the entire frame. .transform() allows input functions as: a NumPy function, a string function name or a user defined function.
In [183]: tsdf.transform(np.abs)Out[183]:A B C2000-01-01 1.219234 1.652700 0.6982772000-01-02 1.858653 0.738520 0.6303642000-01-03 0.112596 1.525897 1.3642252000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.527790 1.715506 0.3872742000-01-09 0.569341 0.569386 0.1341362000-01-10 0.413993 0.862280 0.662690In [184]: tsdf.transform('abs')Out[184]:A B C2000-01-01 1.219234 1.652700 0.6982772000-01-02 1.858653 0.738520 0.6303642000-01-03 0.112596 1.525897 1.3642252000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.527790 1.715506 0.3872742000-01-09 0.569341 0.569386 0.1341362000-01-10 0.413993 0.862280 0.662690In [185]: tsdf.transform(lambda x: x.abs())Out[185]:A B C2000-01-01 1.219234 1.652700 0.6982772000-01-02 1.858653 0.738520 0.6303642000-01-03 0.112596 1.525897 1.3642252000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.527790 1.715506 0.3872742000-01-09 0.569341 0.569386 0.1341362000-01-10 0.413993 0.862280 0.662690
Here transform() received a single function; this is equivalent to a ufunc application.
In [186]: np.abs(tsdf)Out[186]:A B C2000-01-01 1.219234 1.652700 0.6982772000-01-02 1.858653 0.738520 0.6303642000-01-03 0.112596 1.525897 1.3642252000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.527790 1.715506 0.3872742000-01-09 0.569341 0.569386 0.1341362000-01-10 0.413993 0.862280 0.662690
Passing a single function to .transform() with a Series will yield a single Series in return.
In [187]: tsdf.A.transform(np.abs)Out[187]:2000-01-01 1.2192342000-01-02 1.8586532000-01-03 0.1125962000-01-04 NaN2000-01-05 NaN2000-01-06 NaN2000-01-07 NaN2000-01-08 0.5277902000-01-09 0.5693412000-01-10 0.413993Freq: D, Name: A, dtype: float64
Transform with multiple functions
Passing multiple functions will yield a column MultiIndexed DataFrame. The first level will be the original frame column names; the second level will be the names of the transforming functions.
In [188]: tsdf.transform([np.abs, lambda x: x + 1])Out[188]:A B Cabsolute <lambda> absolute <lambda> absolute <lambda>2000-01-01 1.219234 -0.219234 1.652700 -0.652700 0.698277 0.3017232000-01-02 1.858653 2.858653 0.738520 0.261480 0.630364 1.6303642000-01-03 0.112596 0.887404 1.525897 2.525897 1.364225 2.3642252000-01-04 NaN NaN NaN NaN NaN NaN2000-01-05 NaN NaN NaN NaN NaN NaN2000-01-06 NaN NaN NaN NaN NaN NaN2000-01-07 NaN NaN NaN NaN NaN NaN2000-01-08 0.527790 0.472210 1.715506 -0.715506 0.387274 1.3872742000-01-09 0.569341 0.430659 0.569386 1.569386 0.134136 1.1341362000-01-10 0.413993 0.586007 0.862280 0.137720 0.662690 1.662690
Passing multiple functions to a Series will yield a DataFrame. The resulting column names will be the transforming functions.
In [189]: tsdf.A.transform([np.abs, lambda x: x + 1])Out[189]:absolute <lambda>2000-01-01 1.219234 -0.2192342000-01-02 1.858653 2.8586532000-01-03 0.112596 0.8874042000-01-04 NaN NaN2000-01-05 NaN NaN2000-01-06 NaN NaN2000-01-07 NaN NaN2000-01-08 0.527790 0.4722102000-01-09 0.569341 0.4306592000-01-10 0.413993 0.586007
Transforming with a dict
Passing a dict of functions will allow selective transforming per column.
In [190]: tsdf.transform({'A': np.abs, 'B': lambda x: x + 1})Out[190]:A B2000-01-01 1.219234 -0.6527002000-01-02 1.858653 0.2614802000-01-03 0.112596 2.5258972000-01-04 NaN NaN2000-01-05 NaN NaN2000-01-06 NaN NaN2000-01-07 NaN NaN2000-01-08 0.527790 -0.7155062000-01-09 0.569341 1.5693862000-01-10 0.413993 0.137720
Passing a dict of lists will generate a MultiIndexed DataFrame with these selective transforms.
In [191]: tsdf.transform({'A': np.abs, 'B': [lambda x: x + 1, 'sqrt']})Out[191]:A Babsolute <lambda> sqrt2000-01-01 1.219234 -0.652700 NaN2000-01-02 1.858653 0.261480 NaN2000-01-03 0.112596 2.525897 1.2352722000-01-04 NaN NaN NaN2000-01-05 NaN NaN NaN2000-01-06 NaN NaN NaN2000-01-07 NaN NaN NaN2000-01-08 0.527790 -0.715506 NaN2000-01-09 0.569341 1.569386 0.7545772000-01-10 0.413993 0.137720 NaN
Applying Elementwise Functions
Since not all functions can be vectorized (accept NumPy arrays and return another array or value), the methods applymap() on DataFrame and analogously map() on Series accept any Python function taking a single value and returning a single value. For example:
In [192]: df4Out[192]:one two threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [193]: def f(x):.....: return len(str(x)).....:In [194]: df4['one'].map(f)Out[194]:a 18b 19c 18d 3Name: one, dtype: int64In [195]: df4.applymap(f)Out[195]:one two threea 18 19 3b 19 18 19c 18 18 21d 3 18 19
Series.map() has an additional feature; it can be used to easily “link” or “map” values defined by a secondary series. This is closely related to merging/joining functionality:
In [196]: s = pd.Series(['six', 'seven', 'six', 'seven', 'six'],.....: index=['a', 'b', 'c', 'd', 'e']).....:In [197]: t = pd.Series({'six': 6., 'seven': 7.})In [198]: sOut[198]:a sixb sevenc sixd sevene sixdtype: objectIn [199]: s.map(t)Out[199]:a 6.0b 7.0c 6.0d 7.0e 6.0dtype: float64
Reindexing and altering labels
reindex() is the fundamental data alignment method in pandas. It is used to implement nearly all other features relying on label-alignment functionality. To reindex means to conform the data to match a given set of labels along a particular axis. This accomplishes several things:
- Reorders the existing data to match a new set of labels
- Inserts missing value (NA) markers in label locations where no data for that label existed
- If specified, fill data for missing labels using logic (highly relevant to working with time series data)
Here is a simple example:
In [200]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])In [201]: sOut[201]:a -0.368437b -0.036473c 0.774830d -0.310545e 0.709717dtype: float64In [202]: s.reindex(['e', 'b', 'f', 'd'])Out[202]:e 0.709717b -0.036473f NaNd -0.310545dtype: float64
Here, the f label was not contained in the Series and hence appears as NaN in the result.
With a DataFrame, you can simultaneously reindex the index and columns:
In [203]: dfOut[203]:one two threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [204]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])Out[204]:three two onec -0.007090 0.924515 0.797268f NaN NaN NaNb 0.395023 1.045911 -0.356470
You may also use reindex with an axis keyword:
In [205]: df.reindex(['c', 'f', 'b'], axis='index')Out[205]:one two threec 0.797268 0.924515 -0.007090f NaN NaN NaNb -0.356470 1.045911 0.395023
Note that the Index objects containing the actual axis labels can be shared between objects. So if we have a Series and a DataFrame, the following can be done:
In [206]: rs = s.reindex(df.index)In [207]: rsOut[207]:a -0.368437b -0.036473c 0.774830d -0.310545dtype: float64In [208]: rs.index is df.indexOut[208]: True
This means that the reindexed Series’s index is the same Python object as the DataFrame’s index.
New in version 0.21.0.
DataFrame.reindex() also supports an “axis-style” calling convention, where you specify a single labels argument and the axis it applies to.
In [209]: df.reindex(['c', 'f', 'b'], axis='index')Out[209]:one two threec 0.797268 0.924515 -0.007090f NaN NaN NaNb -0.356470 1.045911 0.395023In [210]: df.reindex(['three', 'two', 'one'], axis='columns')Out[210]:three two onea NaN -1.643041 1.400810b 0.395023 1.045911 -0.356470c -0.007090 0.924515 0.797268d -1.670830 1.553693 NaN
::: tip See also MultiIndex / Advanced Indexing is an even more concise way of doing reindexing. :::
::: tip Note When writing performance-sensitive code, there is a good reason to spend some time becoming a reindexing ninja: many operations are faster on pre-aligned data. Adding two unaligned DataFrames internally triggers a reindexing step. For exploratory analysis you will hardly notice the difference (because reindex has been heavily optimized), but when CPU cycles matter sprinkling a few explicit reindex calls here and there can have an impact. :::
Reindexing to align with another object
You may wish to take an object and reindex its axes to be labeled the same as another object. While the syntax for this is straightforward albeit verbose, it is a common enough operation that the reindex_like() method is available to make this simpler:
In [211]: df2Out[211]:one twoa 1.400810 -1.643041b -0.356470 1.045911c 0.797268 0.924515In [212]: df3Out[212]:one twoa 0.786941 -1.752170b -0.970339 0.936783c 0.183399 0.815387In [213]: df.reindex_like(df2)Out[213]:one twoa 1.400810 -1.643041b -0.356470 1.045911c 0.797268 0.924515
Aligning objects with each other with align
The align() method is the fastest way to simultaneously align two objects. It supports a join argument (related to joining and merging):
join='outer': take the union of the indexes (default)join='left': use the calling object’s indexjoin='right': use the passed object’s indexjoin='inner': intersect the indexes
It returns a tuple with both of the reindexed Series:
In [214]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])In [215]: s1 = s[:4]In [216]: s2 = s[1:]In [217]: s1.align(s2)Out[217]:(a -0.610263b -0.170883c 0.367255d 0.273860e NaNdtype: float64, a NaNb -0.170883c 0.367255d 0.273860e 0.314782dtype: float64)In [218]: s1.align(s2, join='inner')Out[218]:(b -0.170883c 0.367255d 0.273860dtype: float64, b -0.170883c 0.367255d 0.273860dtype: float64)In [219]: s1.align(s2, join='left')Out[219]:(a -0.610263b -0.170883c 0.367255d 0.273860dtype: float64, a NaNb -0.170883c 0.367255d 0.273860dtype: float64)
For DataFrames, the join method will be applied to both the index and the columns by default:
In [220]: df.align(df2, join='inner')Out[220]:( one twoa 1.400810 -1.643041b -0.356470 1.045911c 0.797268 0.924515, one twoa 1.400810 -1.643041b -0.356470 1.045911c 0.797268 0.924515)
You can also pass an axis option to only align on the specified axis:
In [221]: df.align(df2, join='inner', axis=0)Out[221]:( one two threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090, one twoa 1.400810 -1.643041b -0.356470 1.045911c 0.797268 0.924515)
If you pass a Series to DataFrame.align(), you can choose to align both objects either on the DataFrame’s index or columns using the axis argument:
In [222]: df.align(df2.iloc[0], axis=1)Out[222]:( one three twoa 1.400810 NaN -1.643041b -0.356470 0.395023 1.045911c 0.797268 -0.007090 0.924515d NaN -1.670830 1.553693, one 1.400810three NaNtwo -1.643041Name: a, dtype: float64)
Filling while reindexing
reindex() takes an optional parameter method which is a filling method chosen from the following table:
| Method | Action |
|---|---|
| pad / ffill | Fill values forward |
| bfill / backfill | Fill values backward |
| nearest | Fill from the nearest index value |
We illustrate these fill methods on a simple Series:
In [223]: rng = pd.date_range('1/3/2000', periods=8)In [224]: ts = pd.Series(np.random.randn(8), index=rng)In [225]: ts2 = ts[[0, 3, 6]]In [226]: tsOut[226]:2000-01-03 -0.0825782000-01-04 0.7685542000-01-05 0.3988422000-01-06 -0.3579562000-01-07 0.1564032000-01-08 -1.3475642000-01-09 0.2535062000-01-10 1.228964Freq: D, dtype: float64In [227]: ts2Out[227]:2000-01-03 -0.0825782000-01-06 -0.3579562000-01-09 0.253506dtype: float64In [228]: ts2.reindex(ts.index)Out[228]:2000-01-03 -0.0825782000-01-04 NaN2000-01-05 NaN2000-01-06 -0.3579562000-01-07 NaN2000-01-08 NaN2000-01-09 0.2535062000-01-10 NaNFreq: D, dtype: float64In [229]: ts2.reindex(ts.index, method='ffill')Out[229]:2000-01-03 -0.0825782000-01-04 -0.0825782000-01-05 -0.0825782000-01-06 -0.3579562000-01-07 -0.3579562000-01-08 -0.3579562000-01-09 0.2535062000-01-10 0.253506Freq: D, dtype: float64In [230]: ts2.reindex(ts.index, method='bfill')Out[230]:2000-01-03 -0.0825782000-01-04 -0.3579562000-01-05 -0.3579562000-01-06 -0.3579562000-01-07 0.2535062000-01-08 0.2535062000-01-09 0.2535062000-01-10 NaNFreq: D, dtype: float64In [231]: ts2.reindex(ts.index, method='nearest')Out[231]:2000-01-03 -0.0825782000-01-04 -0.0825782000-01-05 -0.3579562000-01-06 -0.3579562000-01-07 -0.3579562000-01-08 0.2535062000-01-09 0.2535062000-01-10 0.253506Freq: D, dtype: float64
These methods require that the indexes are ordered increasing or decreasing.
Note that the same result could have been achieved using fillna (except for method='nearest') or interpolate:
In [232]: ts2.reindex(ts.index).fillna(method='ffill')Out[232]:2000-01-03 -0.0825782000-01-04 -0.0825782000-01-05 -0.0825782000-01-06 -0.3579562000-01-07 -0.3579562000-01-08 -0.3579562000-01-09 0.2535062000-01-10 0.253506Freq: D, dtype: float64
reindex() will raise a ValueError if the index is not monotonically increasing or decreasing. fillna() and interpolate() will not perform any checks on the order of the index.
Limits on filling while reindexing
The limit and tolerance arguments provide additional control over filling while reindexing. Limit specifies the maximum count of consecutive matches:
In [233]: ts2.reindex(ts.index, method='ffill', limit=1)Out[233]:2000-01-03 -0.0825782000-01-04 -0.0825782000-01-05 NaN2000-01-06 -0.3579562000-01-07 -0.3579562000-01-08 NaN2000-01-09 0.2535062000-01-10 0.253506Freq: D, dtype: float64
In contrast, tolerance specifies the maximum distance between the index and indexer values:
In [234]: ts2.reindex(ts.index, method='ffill', tolerance='1 day')Out[234]:2000-01-03 -0.0825782000-01-04 -0.0825782000-01-05 NaN2000-01-06 -0.3579562000-01-07 -0.3579562000-01-08 NaN2000-01-09 0.2535062000-01-10 0.253506Freq: D, dtype: float64
Notice that when used on a DatetimeIndex, TimedeltaIndex or PeriodIndex, tolerance will coerced into a Timedelta if possible. This allows you to specify tolerance with appropriate strings.
Dropping labels from an axis
A method closely related to reindex is the drop() function. It removes a set of labels from an axis:
In [235]: dfOut[235]:one two threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [236]: df.drop(['a', 'd'], axis=0)Out[236]:one two threeb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090In [237]: df.drop(['one'], axis=1)Out[237]:two threea -1.643041 NaNb 1.045911 0.395023c 0.924515 -0.007090d 1.553693 -1.670830
Note that the following also works, but is a bit less obvious / clean:
In [238]: df.reindex(df.index.difference(['a', 'd']))Out[238]:one two threeb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090
Renaming / mapping labels
The rename() method allows you to relabel an axis based on some mapping (a dict or Series) or an arbitrary function.
In [239]: sOut[239]:a -0.610263b -0.170883c 0.367255d 0.273860e 0.314782dtype: float64In [240]: s.rename(str.upper)Out[240]:A -0.610263B -0.170883C 0.367255D 0.273860E 0.314782dtype: float64
If you pass a function, it must return a value when called with any of the labels (and must produce a set of unique values). A dict or Series can also be used:
In [241]: df.rename(columns={'one': 'foo', 'two': 'bar'},.....: index={'a': 'apple', 'b': 'banana', 'd': 'durian'}).....:Out[241]:foo bar threeapple 1.400810 -1.643041 NaNbanana -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090durian NaN 1.553693 -1.670830
If the mapping doesn’t include a column/index label, it isn’t renamed. Note that extra labels in the mapping don’t throw an error.
New in version 0.21.0.
DataFrame.rename() also supports an “axis-style” calling convention, where you specify a single mapper and the axis to apply that mapping to.
In [242]: df.rename({'one': 'foo', 'two': 'bar'}, axis='columns')Out[242]:foo bar threea 1.400810 -1.643041 NaNb -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090d NaN 1.553693 -1.670830In [243]: df.rename({'a': 'apple', 'b': 'banana', 'd': 'durian'}, axis='index')Out[243]:one two threeapple 1.400810 -1.643041 NaNbanana -0.356470 1.045911 0.395023c 0.797268 0.924515 -0.007090durian NaN 1.553693 -1.670830
The rename() method also provides an inplace named parameter that is by default False and copies the underlying data. Pass inplace=True to rename the data in place.
New in version 0.18.0.
Finally, rename() also accepts a scalar or list-like for altering the Series.name attribute.
In [244]: s.rename("scalar-name")Out[244]:a -0.610263b -0.170883c 0.367255d 0.273860e 0.314782Name: scalar-name, dtype: float64
New in version 0.24.0.
The methods rename_axis() and rename_axis() allow specific names of a MultiIndex to be changed (as opposed to the labels).
In [245]: df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6],.....: 'y': [10, 20, 30, 40, 50, 60]},.....: index=pd.MultiIndex.from_product([['a', 'b', 'c'], [1, 2]],.....: names=['let', 'num'])).....:In [246]: dfOut[246]:x ylet numa 1 1 102 2 20b 1 3 302 4 40c 1 5 502 6 60In [247]: df.rename_axis(index={'let': 'abc'})Out[247]:x yabc numa 1 1 102 2 20b 1 3 302 4 40c 1 5 502 6 60In [248]: df.rename_axis(index=str.upper)Out[248]:x yLET NUMa 1 1 102 2 20b 1 3 302 4 40c 1 5 502 6 60
Iteration
The behavior of basic iteration over pandas objects depends on the type. When iterating over a Series, it is regarded as array-like, and basic iteration produces the values. Other data structures, like DataFrame and Panel, follow the dict-like convention of iterating over the “keys” of the objects.
In short, basic iteration (for i in object) produces:
- Series: values
- DataFrame: column labels
- Panel: item labels
Thus, for example, iterating over a DataFrame gives you the column names:
In [249]: df = pd.DataFrame({'col1': np.random.randn(3),.....: 'col2': np.random.randn(3)}, index=['a', 'b', 'c']).....:In [250]: for col in df:.....: print(col).....:col1col2
Pandas objects also have the dict-like iteritems() method to iterate over the (key, value) pairs.
To iterate over the rows of a DataFrame, you can use the following methods:
- iterrows(): Iterate over the rows of a DataFrame as (index, Series) pairs. This converts the rows to Series objects, which can change the dtypes and has some performance implications.
- itertuples(): Iterate over the rows of a DataFrame as namedtuples of the values. This is a lot faster than iterrows(), and is in most cases preferable to use to iterate over the values of a DataFrame.
::: Warning Warning Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided with one of the following approaches:
- Look for a vectorized solution: many operations can be performed using built-in methods or NumPy functions, (boolean) indexing, …
- When you have a function that cannot work on the full DataFrame/Series at once, it is better to use apply() instead of iterating over the values. See the docs on function application.
- If you need to do iterative manipulations on the values but performance is important, consider writing the inner loop with cython or numba. See the enhancing performance section for some examples of this approach. :::
::: warning Warning Warning You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect!
For example, in the following case setting the value has no effect:
In [251]: df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c']})In [252]: for index, row in df.iterrows():.....: row['a'] = 10.....:In [253]: dfOut[253]:a b0 1 a1 2 b2 3 c
:::
iteritems
Consistent with the dict-like interface, iteritems() iterates through key-value pairs:
- Series: (index, scalar value) pairs
- DataFrame: (column, Series) pairs
- Panel: (item, DataFrame) pairs
For example:
In [254]: for item, frame in wp.iteritems():.....: print(item).....: print(frame).....:Item1A B C D2000-01-01 -1.157892 -1.344312 0.844885 1.0757702000-01-02 -0.109050 1.643563 -1.469388 0.3570212000-01-03 -0.674600 -1.776904 -0.968914 -1.2945242000-01-04 0.413738 0.276662 -0.472035 -0.0139602000-01-05 -0.362543 -0.006154 -0.923061 0.895717Item2A B C D2000-01-01 0.805244 -1.206412 2.565646 1.4312562000-01-02 1.340309 -1.170299 -0.226169 0.4108352000-01-03 0.813850 0.132003 -0.827317 -0.0764672000-01-04 -1.187678 1.130127 -1.436737 -1.4136812000-01-05 1.607920 1.024180 0.569605 0.875906
iterrows
iterrows() allows you to iterate through the rows of a DataFrame as Series objects. It returns an iterator yielding each index value along with a Series containing the data in each row:
In [255]: for row_index, row in df.iterrows():.....: print(row_index, row, sep='\n').....:0a 1b aName: 0, dtype: object1a 2b bName: 1, dtype: object2a 3b cName: 2, dtype: object
::: tip Note Because iterrows() returns a Series for each row, it does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames). For example,
In [256]: df_orig = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])In [257]: df_orig.dtypesOut[257]:int int64float float64dtype: objectIn [258]: row = next(df_orig.iterrows())[1]In [259]: rowOut[259]:int 1.0float 1.5Name: 0, dtype: float64
All values in row, returned as a Series, are now upcasted to floats, also the original integer value in column x:
In [260]: row['int'].dtypeOut[260]: dtype('float64')In [261]: df_orig['int'].dtypeOut[261]: dtype('int64')
To preserve dtypes while iterating over the rows, it is better to use itertuples() which returns namedtuples of the values and which is generally much faster than iterrows(). :::
For instance, a contrived way to transpose the DataFrame would be:
In [262]: df2 = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})In [263]: print(df2)x y0 1 41 2 52 3 6In [264]: print(df2.T)0 1 2x 1 2 3y 4 5 6In [265]: df2_t = pd.DataFrame({idx: values for idx, values in df2.iterrows()})In [266]: print(df2_t)0 1 2x 1 2 3y 4 5 6
itertuples
The itertuples() method will return an iterator yielding a namedtuple for each row in the DataFrame. The first element of the tuple will be the row’s corresponding index value, while the remaining values are the row values.
For instance:
In [267]: for row in df.itertuples():.....: print(row).....:Pandas(Index=0, a=1, b='a')Pandas(Index=1, a=2, b='b')Pandas(Index=2, a=3, b='c')
This method does not convert the row to a Series object; it merely returns the values inside a namedtuple. Therefore, itertuples() preserves the data type of the values and is generally faster as iterrows().
::: tip Note The column names will be renamed to positional names if they are invalid Python identifiers, repeated, or start with an underscore. With a large number of columns (>255), regular tuples are returned. :::
.dt accessor
Series has an accessor to succinctly return datetime like properties for the values of the Series, if it is a datetime/period like Series. This will return a Series, indexed like the existing Series.
# datetimeIn [268]: s = pd.Series(pd.date_range('20130101 09:10:12', periods=4))In [269]: sOut[269]:0 2013-01-01 09:10:121 2013-01-02 09:10:122 2013-01-03 09:10:123 2013-01-04 09:10:12dtype: datetime64[ns]In [270]: s.dt.hourOut[270]:0 91 92 93 9dtype: int64In [271]: s.dt.secondOut[271]:0 121 122 123 12dtype: int64In [272]: s.dt.dayOut[272]:0 11 22 33 4dtype: int64
This enables nice expressions like this:
In [273]: s[s.dt.day == 2]Out[273]:1 2013-01-02 09:10:12dtype: datetime64[ns]
You can easily produces tz aware transformations:
In [274]: stz = s.dt.tz_localize('US/Eastern')In [275]: stzOut[275]:0 2013-01-01 09:10:12-05:001 2013-01-02 09:10:12-05:002 2013-01-03 09:10:12-05:003 2013-01-04 09:10:12-05:00dtype: datetime64[ns, US/Eastern]In [276]: stz.dt.tzOut[276]: <DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>
You can also chain these types of operations:
In [277]: s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')Out[277]:0 2013-01-01 04:10:12-05:001 2013-01-02 04:10:12-05:002 2013-01-03 04:10:12-05:003 2013-01-04 04:10:12-05:00dtype: datetime64[ns, US/Eastern]
You can also format datetime values as strings with Series.dt.strftime() which supports the same format as the standard strftime().
# DatetimeIndexIn [278]: s = pd.Series(pd.date_range('20130101', periods=4))In [279]: sOut[279]:0 2013-01-011 2013-01-022 2013-01-033 2013-01-04dtype: datetime64[ns]In [280]: s.dt.strftime('%Y/%m/%d')Out[280]:0 2013/01/011 2013/01/022 2013/01/033 2013/01/04dtype: object
# PeriodIndexIn [281]: s = pd.Series(pd.period_range('20130101', periods=4))In [282]: sOut[282]:0 2013-01-011 2013-01-022 2013-01-033 2013-01-04dtype: period[D]In [283]: s.dt.strftime('%Y/%m/%d')Out[283]:0 2013/01/011 2013/01/022 2013/01/033 2013/01/04dtype: object
The .dt accessor works for period and timedelta dtypes.
# periodIn [284]: s = pd.Series(pd.period_range('20130101', periods=4, freq='D'))In [285]: sOut[285]:0 2013-01-011 2013-01-022 2013-01-033 2013-01-04dtype: period[D]In [286]: s.dt.yearOut[286]:0 20131 20132 20133 2013dtype: int64In [287]: s.dt.dayOut[287]:0 11 22 33 4dtype: int64
# timedeltaIn [288]: s = pd.Series(pd.timedelta_range('1 day 00:00:05', periods=4, freq='s'))In [289]: sOut[289]:0 1 days 00:00:051 1 days 00:00:062 1 days 00:00:073 1 days 00:00:08dtype: timedelta64[ns]In [290]: s.dt.daysOut[290]:0 11 12 13 1dtype: int64In [291]: s.dt.secondsOut[291]:0 51 62 73 8dtype: int64In [292]: s.dt.componentsOut[292]:days hours minutes seconds milliseconds microseconds nanoseconds0 1 0 0 5 0 0 01 1 0 0 6 0 0 02 1 0 0 7 0 0 03 1 0 0 8 0 0 0
::: tip Note
Series.dt will raise a TypeError if you access with a non-datetime-like values.
:::
Vectorized string methods
Series is equipped with a set of string processing methods that make it easy to operate on each element of the array. Perhaps most importantly, these methods exclude missing/NA values automatically. These are accessed via the Series’s str attribute and generally have names matching the equivalent (scalar) built-in string methods. For example:
In [293]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])In [294]: s.str.lower()Out[294]:0 a1 b2 c3 aaba4 baca5 NaN6 caba7 dog8 catdtype: object
Powerful pattern-matching methods are provided as well, but note that pattern-matching generally uses regular expressions by default (and in some cases always uses them).
Please see Vectorized String Methods for a complete description.
Sorting
Pandas supports three kinds of sorting: sorting by index labels, sorting by column values, and sorting by a combination of both.
By Index
The Series.sort_index() and DataFrame.sort_index() methods are used to sort a pandas object by its index levels.
In [295]: df = pd.DataFrame({.....: 'one': pd.Series(np.random.randn(3), index=['a', 'b', 'c']),.....: 'two': pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),.....: 'three': pd.Series(np.random.randn(3), index=['b', 'c', 'd'])}).....:In [296]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],.....: columns=['three', 'two', 'one']).....:In [297]: unsorted_dfOut[297]:three two onea NaN -0.867293 0.050162d 1.215473 -0.051744 NaNc -0.421091 -0.712097 0.953102b 1.205223 0.632624 -1.534113# DataFrameIn [298]: unsorted_df.sort_index()Out[298]:three two onea NaN -0.867293 0.050162b 1.205223 0.632624 -1.534113c -0.421091 -0.712097 0.953102d 1.215473 -0.051744 NaNIn [299]: unsorted_df.sort_index(ascending=False)Out[299]:three two oned 1.215473 -0.051744 NaNc -0.421091 -0.712097 0.953102b 1.205223 0.632624 -1.534113a NaN -0.867293 0.050162In [300]: unsorted_df.sort_index(axis=1)Out[300]:one three twoa 0.050162 NaN -0.867293d NaN 1.215473 -0.051744c 0.953102 -0.421091 -0.712097b -1.534113 1.205223 0.632624# SeriesIn [301]: unsorted_df['three'].sort_index()Out[301]:a NaNb 1.205223c -0.421091d 1.215473Name: three, dtype: float64
By Values
The Series.sort_values() method is used to sort a Series by its values. The DataFrame.sort_values() method is used to sort a DataFrame by its column or row values. The optional by parameter to DataFrame.sort_values() may used to specify one or more columns to use to determine the sorted order.
In [302]: df1 = pd.DataFrame({'one': [2, 1, 1, 1],.....: 'two': [1, 3, 2, 4],.....: 'three': [5, 4, 3, 2]}).....:In [303]: df1.sort_values(by='two')Out[303]:one two three0 2 1 52 1 2 31 1 3 43 1 4 2
The by parameter can take a list of column names, e.g.:
In [304]: df1[['one', 'two', 'three']].sort_values(by=['one', 'two'])Out[304]:one two three2 1 2 31 1 3 43 1 4 20 2 1 5
These methods have special treatment of NA values via the na_position argument:
In [305]: s[2] = np.nanIn [306]: s.sort_values()Out[306]:0 A3 Aaba1 B4 Baca6 CABA8 cat7 dog2 NaN5 NaNdtype: objectIn [307]: s.sort_values(na_position='first')Out[307]:2 NaN5 NaN0 A3 Aaba1 B4 Baca6 CABA8 cat7 dogdtype: object
By Indexes and Values
New in version 0.23.0.
Strings passed as the by parameter to DataFrame.sort_values() may refer to either columns or index level names.
# Build MultiIndexIn [308]: idx = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('a', 2),.....: ('b', 2), ('b', 1), ('b', 1)]).....:In [309]: idx.names = ['first', 'second']# Build DataFrameIn [310]: df_multi = pd.DataFrame({'A': np.arange(6, 0, -1)},.....: index=idx).....:In [311]: df_multiOut[311]:Afirst seconda 1 62 52 4b 2 31 21 1
Sort by ‘second’ (index) and ‘A’ (column)
In [312]: df_multi.sort_values(by=['second', 'A'])Out[312]:Afirst secondb 1 11 2a 1 6b 2 3a 2 42 5
::: tip Note Note If a string matches both a column name and an index level name then a warning is issued and the column takes precedence. This will result in an ambiguity error in a future version. :::
searchsorted
Series has the searchsorted() method, which works similarly to numpy.ndarray.searchsorted().
In [313]: ser = pd.Series([1, 2, 3])In [314]: ser.searchsorted([0, 3])Out[314]: array([0, 2])In [315]: ser.searchsorted([0, 4])Out[315]: array([0, 3])In [316]: ser.searchsorted([1, 3], side='right')Out[316]: array([1, 3])In [317]: ser.searchsorted([1, 3], side='left')Out[317]: array([0, 2])In [318]: ser = pd.Series([3, 1, 2])In [319]: ser.searchsorted([0, 3], sorter=np.argsort(ser))Out[319]: array([0, 2])
smallest / largest values
Series has the nsmallest() and nlargest() methods which return the smallest or largest 𝑛 values. For a large Series this can be much faster than sorting the entire Series and calling head(n) on the result.
In [320]: s = pd.Series(np.random.permutation(10))In [321]: sOut[321]:0 51 32 23 04 75 66 97 18 49 8dtype: int64In [322]: s.sort_values()Out[322]:3 07 12 21 38 40 55 64 79 86 9dtype: int64In [323]: s.nsmallest(3)Out[323]:3 07 12 2dtype: int64In [324]: s.nlargest(3)Out[324]:6 99 84 7dtype: int64
DataFrame also has the nlargest and nsmallest methods.
In [325]: df = pd.DataFrame({'a': [-2, -1, 1, 10, 8, 11, -1],.....: 'b': list('abdceff'),.....: 'c': [1.0, 2.0, 4.0, 3.2, np.nan, 3.0, 4.0]}).....:In [326]: df.nlargest(3, 'a')Out[326]:a b c5 11 f 3.03 10 c 3.24 8 e NaNIn [327]: df.nlargest(5, ['a', 'c'])Out[327]:a b c5 11 f 3.03 10 c 3.24 8 e NaN2 1 d 4.06 -1 f 4.0In [328]: df.nsmallest(3, 'a')Out[328]:a b c0 -2 a 1.01 -1 b 2.06 -1 f 4.0In [329]: df.nsmallest(5, ['a', 'c'])Out[329]:a b c0 -2 a 1.01 -1 b 2.06 -1 f 4.02 1 d 4.04 8 e NaN
Sorting by a MultiIndex column
You must be explicit about sorting when the column is a MultiIndex, and fully specify all levels to by.
In [330]: df1.columns = pd.MultiIndex.from_tuples([('a', 'one'),.....: ('a', 'two'),.....: ('b', 'three')]).....:In [331]: df1.sort_values(by=('a', 'two'))Out[331]:a bone two three0 2 1 52 1 2 31 1 3 43 1 4 2
Copying
The copy() method on pandas objects copies the underlying data (though not the axis indexes, since they are immutable) and returns a new object. Note that it is seldom necessary to copy objects. For example, there are only a handful of ways to alter a DataFrame in-place:
- Inserting, deleting, or modifying a column.
- Assigning to the
indexorcolumnsattributes. - 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 object untouched. If the data is modified, it is because you did so explicitly.
dtypes
For the most part, pandas uses NumPy arrays and dtypes for Series or individual columns of a DataFrame. NumPy provides support for float, int, bool, timedelta64[ns] and datetime64[ns] (note that NumPy does not support timezone-aware datetimes).
Pandas and third-party libraries extend NumPy’s type system in a few places. This section describes the extensions pandas has made internally. See Extension Types for how to write your own extension that works with pandas. See Extension Data Types for a list of third-party libraries that have implemented an extension.
The following table lists all of pandas extension types. See the respective documentation sections for more on each type.
| Kind of Data | Data Type | Scalar | Array | Documentation |
|---|---|---|---|---|
| tz-aware datetime | DatetimeTZDtype | Timestamp | arrays.DatetimeArray | Time Zone Handling |
| Categorical | CategoricalDtype | (none) | Categorical | Categorical Data |
| period (time spans) | PeriodDtype | Period | arrays.PeriodArray | Time Span Representation |
| sparse | SparseDtype | (none) | arrays.SparseArray | Sparse data structures |
| intervals | IntervalDtype | Interval | arrays.IntervalArray | IntervalIndex |
| nullable integer | Int64Dtype, … | (none) | arrays.IntegerArray | Nullable Integer Data Type |
Pandas uses the object dtype for storing strings.
Finally, arbitrary objects may be stored using the object dtype, but should be avoided to the extent possible (for performance and interoperability with other libraries and methods. See object conversion).
A convenient dtypes attribute for DataFrame returns a Series with the data type of each column.
In [332]: dft = pd.DataFrame({'A': np.random.rand(3),.....: 'B': 1,.....: 'C': 'foo',.....: 'D': pd.Timestamp('20010102'),.....: 'E': pd.Series([1.0] * 3).astype('float32'),.....: 'F': False,.....: 'G': pd.Series([1] * 3, dtype='int8')}).....:In [333]: dftOut[333]:A B C D E F G0 0.278831 1 foo 2001-01-02 1.0 False 11 0.242124 1 foo 2001-01-02 1.0 False 12 0.078031 1 foo 2001-01-02 1.0 False 1In [334]: dft.dtypesOut[334]:A float64B int64C objectD datetime64[ns]E float32F boolG int8dtype: object
On a Series object, use the dtype attribute.
In [335]: dft['A'].dtypeOut[335]: dtype('float64')
If a pandas object contains data with multiple dtypes in a single column, the dtype of the column will be chosen to accommodate all of the data types (object is the most general).
# these ints are coerced to floatsIn [336]: pd.Series([1, 2, 3, 4, 5, 6.])Out[336]:0 1.01 2.02 3.03 4.04 5.05 6.0dtype: float64# string data forces an ``object`` dtypeIn [337]: pd.Series([1, 2, 3, 6., 'foo'])Out[337]:0 11 22 33 64 foodtype: object
The number of columns of each type in a DataFrame can be found by calling get_dtype_counts().
In [338]: dft.get_dtype_counts()Out[338]:float64 1float32 1int64 1int8 1datetime64[ns] 1bool 1object 1dtype: 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.
Frame(np.random.randn(8, 1), columns=['A'], dtype='float32')In [340]: df1Out[340]:A0 -1.6413391 -0.3140622 -0.6792063 1.1782434 0.1817905 -2.0442486 1.1512827 -1.641398In [341]: df1.dtypesOut[341]:A float32dtype: objectIn [342]: df2 = pd.DataFrame({'A': pd.Series(np.random.randn(8), dtype='float16'),.....: 'B': pd.Series(np.random.randn(8)),.....: 'C': pd.Series(np.array(np.random.randn(8),.....: dtype='uint8'))}).....:In [343]: df2Out[343]:A B C0 0.130737 -1.143729 11 0.289551 2.787500 02 0.590820 -0.708143 2543 -0.020142 -1.512388 04 -1.048828 -0.243145 15 -0.808105 -0.650992 06 1.373047 2.090108 07 -0.254395 0.433098 0In [344]: df2.dtypesOut[344]:A float16B float64C uint8dtype: object
defaults
By default integer types are int64 and float types are float64, regardless of platform (32-bit or 64-bit). The following will all result in int64 dtypes.
In [345]: pd.DataFrame([1, 2], columns=['a']).dtypesOut[345]:a int64dtype: objectIn [346]: pd.DataFrame({'a': [1, 2]}).dtypesOut[346]:a int64dtype: objectIn [347]: pd.DataFrame({'a': 1}, index=list(range(2))).dtypesOut[347]:a int64dtype: object
Note that Numpy will choose platform-dependent types when creating arrays. The following WILL result in int32 on 32-bit platform.
In [348]: frame = pd.DataFrame(np.array([1, 2]))
upcasting
Types can potentially be upcasted when combined with other types, meaning they are promoted from the current type (e.g. int to float).
In [349]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2In [350]: df3Out[350]:A B C0 -1.510602 -1.143729 1.01 -0.024511 2.787500 0.02 -0.088385 -0.708143 254.03 1.158101 -1.512388 0.04 -0.867039 -0.243145 1.05 -2.852354 -0.650992 0.06 2.524329 2.090108 0.07 -1.895793 0.433098 0.0In [351]: df3.dtypesOut[351]:A float32B float64C float64dtype: object
DataFrame.to_numpy() will return the lower-common-denominator of the dtypes, meaning the dtype that can accommodate ALL of the types in the resulting homogeneous dtyped NumPy array. This can force some upcasting.
In [352]: df3.to_numpy().dtypeOut[352]: dtype('float64')
astype
You can use the astype() method to explicitly convert dtypes from one to another. These will by default return a copy, even if the dtype was unchanged (pass copy=False to change this behavior). In addition, they will raise an exception if the astype operation is invalid.
Upcasting is always according to the numpy rules. If two different dtypes are involved in an operation, then the more general one will be used as the result of the operation.
In [353]: df3Out[353]:A B C0 -1.510602 -1.143729 1.01 -0.024511 2.787500 0.02 -0.088385 -0.708143 254.03 1.158101 -1.512388 0.04 -0.867039 -0.243145 1.05 -2.852354 -0.650992 0.06 2.524329 2.090108 0.07 -1.895793 0.433098 0.0In [354]: df3.dtypesOut[354]:A float32B float64C float64dtype: object# conversion of dtypesIn [355]: df3.astype('float32').dtypesOut[355]:A float32B float32C float32dtype: object
Convert a subset of columns to a specified type using astype().
In [356]: dft = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})In [357]: dft[['a', 'b']] = dft[['a', 'b']].astype(np.uint8)In [358]: dftOut[358]:a b c0 1 4 71 2 5 82 3 6 9In [359]: dft.dtypesOut[359]:a uint8b uint8c int64dtype: object
New in version 0.19.0.
Convert certain columns to a specific dtype by passing a dict to astype().
In [360]: dft1 = pd.DataFrame({'a': [1, 0, 1], 'b': [4, 5, 6], 'c': [7, 8, 9]})In [361]: dft1 = dft1.astype({'a': np.bool, 'c': np.float64})In [362]: dft1Out[362]:a b c0 True 4 7.01 False 5 8.02 True 6 9.0In [363]: dft1.dtypesOut[363]:a boolb int64c float64dtype: object
::: tip Note
When trying to convert a subset of columns to a specified type using astype() and loc(), upcasting occurs.
loc() tries to fit in what we are assigning to the current dtypes, while [] will overwrite them taking the dtype from the right hand side. Therefore the following piece of code produces the unintended result.
In [364]: dft = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]})In [365]: dft.loc[:, ['a', 'b']].astype(np.uint8).dtypesOut[365]:a uint8b uint8dtype: objectIn [366]: dft.loc[:, ['a', 'b']] = dft.loc[:, ['a', 'b']].astype(np.uint8)In [367]: dft.dtypesOut[367]:a int64b int64c int64dtype: object
:::
object conversion
pandas offers various functions to try to force conversion of types from the object dtype to other types. In cases where the data is already of the correct type, but stored in an object array, the DataFrame.infer_objects() and Series.infer_objects() methods can be used to soft convert to the correct type.
In [368]: import datetimeIn [369]: df = pd.DataFrame([[1, 2],.....: ['a', 'b'],.....: [datetime.datetime(2016, 3, 2),.....: datetime.datetime(2016, 3, 2)]]).....:In [370]: df = df.TIn [371]: dfOut[371]:0 1 20 1 a 2016-03-02 00:00:001 2 b 2016-03-02 00:00:00In [372]: df.dtypesOut[372]:0 object1 object2 objectdtype: object
Because the data was transposed the original inference stored all columns as object, which infer_objects will correct.
In [373]: df.infer_objects().dtypesOut[373]:0 int641 object2 datetime64[ns]dtype: object
The following functions are available for one dimensional object arrays or scalars to perform hard conversion of objects to a specified type:
to_numeric() (conversion to numeric dtypes)
In [374]: m = ['1.1', 2, 3]In [375]: pd.to_numeric(m)Out[375]: array([ 1.1, 2. , 3. ])
to_datetime() (conversion to datetime objects)
In [376]: import datetimeIn [377]: m = ['2016-07-09', datetime.datetime(2016, 3, 2)]In [378]: pd.to_datetime(m)Out[378]: DatetimeIndex(['2016-07-09', '2016-03-02'], dtype='datetime64[ns]', freq=None)
to_timedelta() (conversion to timedelta objects)
In [379]: m = ['5us', pd.Timedelta('1day')]In [380]: pd.to_timedelta(m)Out[380]: TimedeltaIndex(['0 days 00:00:00.000005', '1 days 00:00:00'], dtype='timedelta64[ns]', freq=None)
To force a conversion, we can pass in an errors argument, which specifies how pandas should deal with elements that cannot be converted to desired dtype or object. By default, errors='raise', meaning that any errors encountered will be raised during the conversion process. However, if errors='coerce', these errors will be ignored and pandas will convert problematic elements to pd.NaT (for datetime and timedelta) or np.nan (for numeric). This might be useful if you are reading in data which is mostly of the desired dtype (e.g. numeric, datetime), but occasionally has non-conforming elements intermixed that you want to represent as missing:
In [381]: import datetimeIn [382]: m = ['apple', datetime.datetime(2016, 3, 2)]In [383]: pd.to_datetime(m, errors='coerce')Out[383]: DatetimeIndex(['NaT', '2016-03-02'], dtype='datetime64[ns]', freq=None)In [384]: m = ['apple', 2, 3]In [385]: pd.to_numeric(m, errors='coerce')Out[385]: array([ nan, 2., 3.])In [386]: m = ['apple', pd.Timedelta('1day')]In [387]: pd.to_timedelta(m, errors='coerce')Out[387]: TimedeltaIndex([NaT, '1 days'], dtype='timedelta64[ns]', freq=None)
The errors parameter has a third option of errors='ignore', which will simply return the passed in data if it encounters any errors with the conversion to a desired data type:
In [388]: import datetimeIn [389]: m = ['apple', datetime.datetime(2016, 3, 2)]In [390]: pd.to_datetime(m, errors='ignore')Out[390]: Index(['apple', 2016-03-02 00:00:00], dtype='object')In [391]: m = ['apple', 2, 3]In [392]: pd.to_numeric(m, errors='ignore')Out[392]: array(['apple', 2, 3], dtype=object)In [393]: m = ['apple', pd.Timedelta('1day')]In [394]: pd.to_timedelta(m, errors='ignore')Out[394]: array(['apple', Timedelta('1 days 00:00:00')], dtype=object)
In addition to object conversion, to_numeric() provides another argument downcast, which gives the option of downcasting the newly (or already) numeric data to a smaller dtype, which can conserve memory:
In [395]: m = ['1', 2, 3]In [396]: pd.to_numeric(m, downcast='integer') # smallest signed int dtypeOut[396]: array([1, 2, 3], dtype=int8)In [397]: pd.to_numeric(m, downcast='signed') # same as 'integer'Out[397]: array([1, 2, 3], dtype=int8)In [398]: pd.to_numeric(m, downcast='unsigned') # smallest unsigned int dtypeOut[398]: array([1, 2, 3], dtype=uint8)In [399]: pd.to_numeric(m, downcast='float') # smallest float dtypeOut[399]: array([ 1., 2., 3.], dtype=float32)
As these methods apply only to one-dimensional arrays, lists or scalars; they cannot be used directly on multi-dimensional objects such as DataFrames. However, with apply(), we can “apply” the function over each column efficiently:
In [400]: import datetimeIn [401]: df = pd.DataFrame([.....: ['2016-07-09', datetime.datetime(2016, 3, 2)]] * 2, dtype='O').....:In [402]: dfOut[402]:0 10 2016-07-09 2016-03-02 00:00:001 2016-07-09 2016-03-02 00:00:00In [403]: df.apply(pd.to_datetime)Out[403]:0 10 2016-07-09 2016-03-021 2016-07-09 2016-03-02In [404]: df = pd.DataFrame([['1.1', 2, 3]] * 2, dtype='O')In [405]: dfOut[405]:0 1 20 1.1 2 31 1.1 2 3In [406]: df.apply(pd.to_numeric)Out[406]:0 1 20 1.1 2 31 1.1 2 3In [407]: df = pd.DataFrame([['5us', pd.Timedelta('1day')]] * 2, dtype='O')In [408]: dfOut[408]:0 10 5us 1 days 00:00:001 5us 1 days 00:00:00In [409]: df.apply(pd.to_timedelta)Out[409]:0 10 00:00:00.000005 1 days1 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.
In [410]: dfi = df3.astype('int32')In [411]: dfi['E'] = 1In [412]: dfiOut[412]:A B C E0 -1 -1 1 11 0 2 0 12 0 0 254 13 1 -1 0 14 0 0 1 15 -2 0 0 16 2 2 0 17 -1 0 0 1In [413]: dfi.dtypesOut[413]:A int32B int32C int32E int64dtype: objectIn [414]: casted = dfi[dfi > 0]In [415]: castedOut[415]:A B C E0 NaN NaN 1.0 11 NaN 2.0 NaN 12 NaN NaN 254.0 13 1.0 NaN NaN 14 NaN NaN 1.0 15 NaN NaN NaN 16 2.0 2.0 NaN 17 NaN NaN NaN 1In [416]: casted.dtypesOut[416]:A float64B float64C float64E int64dtype: object
While float dtypes are unchanged.
In [417]: dfa = df3.copy()In [418]: dfa['A'] = dfa['A'].astype('float32')In [419]: dfa.dtypesOut[419]:A float32B float64C float64dtype: objectIn [420]: casted = dfa[df2 > 0]In [421]: castedOut[421]:A B C0 -1.510602 NaN 1.01 -0.024511 2.787500 NaN2 -0.088385 NaN 254.03 NaN NaN NaN4 NaN NaN 1.05 NaN NaN NaN6 2.524329 2.090108 NaN7 NaN 0.433098 NaNIn [422]: casted.dtypesOut[422]:A float32B float64C float64dtype: object
Selecting columns based on dtype
The select_dtypes() method implements subsetting of columns based on their dtype.
First, let’s create a DataFrame with a slew of different dtypes:
In [423]: df = pd.DataFrame({'string': list('abc'),.....: 'int64': list(range(1, 4)),.....: 'uint8': np.arange(3, 6).astype('u1'),.....: 'float64': np.arange(4.0, 7.0),.....: 'bool1': [True, False, True],.....: 'bool2': [False, True, False],.....: 'dates': pd.date_range('now', periods=3),.....: 'category': pd.Series(list("ABC")).astype('category')}).....:In [424]: df['tdeltas'] = df.dates.diff()In [425]: df['uint64'] = np.arange(3, 6).astype('u8')In [426]: df['other_dates'] = pd.date_range('20130101', periods=3)In [427]: df['tz_aware_dates'] = pd.date_range('20130101', periods=3, tz='US/Eastern')In [428]: dfOut[428]:string int64 uint8 float64 bool1 bool2 dates category tdeltas uint64 other_dates tz_aware_dates0 a 1 3 4.0 True False 2019-03-12 22:38:38.692567 A NaT 3 2013-01-01 2013-01-01 00:00:00-05:001 b 2 4 5.0 False True 2019-03-13 22:38:38.692567 B 1 days 4 2013-01-02 2013-01-02 00:00:00-05:002 c 3 5 6.0 True False 2019-03-14 22:38:38.692567 C 1 days 5 2013-01-03 2013-01-03 00:00:00-05:00
And the dtypes:
In [429]: df.dtypesOut[429]:string objectint64 int64uint8 uint8float64 float64bool1 boolbool2 booldates datetime64[ns]category categorytdeltas timedelta64[ns]uint64 uint64other_dates datetime64[ns]tz_aware_dates datetime64[ns, US/Eastern]dtype: object
select_dtypes() has two parameters include and exclude that allow you to say “give me the columns with these dtypes” (include) and/or “give the columns without these dtypes” (exclude).
For example, to select bool columns:
In [430]: df.select_dtypes(include=[bool])Out[430]:bool1 bool20 True False1 False True2 True False
You can also pass the name of a dtype in the NumPy dtype hierarchy:
In [431]: df.select_dtypes(include=['bool'])Out[431]:bool1 bool20 True False1 False True2 True False
select_dtypes() also works with generic dtypes as well.
For example, to select all numeric and boolean columns while excluding unsigned integers:
In [432]: df.select_dtypes(include=['number', 'bool'], exclude=['unsignedinteger'])Out[432]:int64 float64 bool1 bool2 tdeltas0 1 4.0 True False NaT1 2 5.0 False True 1 days2 3 6.0 True False 1 days
To select string columns you must use the object dtype:
In [433]: df.select_dtypes(include=['object'])Out[433]:string0 a1 b2 c
To see all the child dtypes of a generic dtype like numpy.number you can define a function that returns a tree of child dtypes:
In [434]: def subdtypes(dtype):.....: subs = dtype.__subclasses__().....: if not subs:.....: return dtype.....: return [dtype, [subdtypes(dt) for dt in subs]].....:
All NumPy dtypes are subclasses of numpy.generic:
In [435]: subdtypes(np.generic)Out[435]:[numpy.generic,[[numpy.number,[[numpy.integer,[[numpy.signedinteger,[numpy.int8,numpy.int16,numpy.int32,numpy.int64,numpy.int64,numpy.timedelta64]],[numpy.unsignedinteger,[numpy.uint8,numpy.uint16,numpy.uint32,numpy.uint64,numpy.uint64]]]],[numpy.inexact,[[numpy.floating,[numpy.float16, numpy.float32, numpy.float64, numpy.float128]],[numpy.complexfloating,[numpy.complex64, numpy.complex128, numpy.complex256]]]]]],[numpy.flexible,[[numpy.character, [numpy.bytes_, numpy.str_]],[numpy.void, [numpy.record]]]],numpy.bool_,numpy.datetime64,numpy.object_]]
::: tip Note
Pandas also defines the types category, and datetime64[ns, tz], which are not integrated into the normal NumPy hierarchy and won’t show up with the above function.
:::
