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 0.229453
1 0.304418
2 0.736135
3 -0.859631
4 -0.424100
dtype: float64
In [7]: long_series.tail(3)
Out[7]:
997 -0.351587
998 1.136249
999 -0.448789
dtype: float64
Attributes and the raw ndarray(s)¶
pandas objects have a number of attributes enabling you to access the metadata
- shape: gives the axis dimensions of the object, consistent with ndarray
- Axis labels
- Series: index (only axis)
- DataFrame: index (rows) and columns
- Panel: items, major_axis, and minor_axis
Note, these attributes can be safely assigned to!
In [8]: df[:2]
Out[8]:
A B C
2000-01-01 0.048869 -1.360687 -0.47901
2000-01-02 -0.859661 -0.231595 -0.52775
In [9]: df.columns = [x.lower() for x in df.columns]
In [10]: df
Out[10]:
a b c
2000-01-01 0.048869 -1.360687 -0.479010
2000-01-02 -0.859661 -0.231595 -0.527750
2000-01-03 -1.296337 0.150680 0.123836
2000-01-04 0.571764 1.555563 -0.823761
2000-01-05 0.535420 -1.032853 1.469725
2000-01-06 1.304124 1.449735 0.203109
2000-01-07 -1.032011 0.969818 -0.962723
2000-01-08 1.382083 -0.938794 0.669142
To get the actual data inside a data structure, one need only access the values property:
In [11]: s.values
Out[11]: array([-1.9339, 0.3773, 0.7341, 2.1416, -0.0112])
In [12]: df.values
Out[12]:
array([[ 0.0489, -1.3607, -0.479 ],
[-0.8597, -0.2316, -0.5278],
[-1.2963, 0.1507, 0.1238],
[ 0.5718, 1.5556, -0.8238],
[ 0.5354, -1.0329, 1.4697],
[ 1.3041, 1.4497, 0.2031],
[-1.032 , 0.9698, -0.9627],
[ 1.3821, -0.9388, 0.6691]])
In [13]: wp.values
Out[13]:
array([[[-0.4336, -0.2736, 0.6804, -0.3084],
[-0.2761, -1.8212, -1.9936, -1.9274],
[-2.0279, 1.625 , 0.5511, 3.0593],
[ 0.4553, -0.0307, 0.9357, 1.0612],
[-2.1079, 0.1999, 0.3236, -0.6416]],
[[-0.5875, 0.0539, 0.1949, -0.382 ],
[ 0.3186, 2.0891, -0.7283, -0.0903],
[-0.7482, 1.3189, -2.0298, 0.7927],
[ 0.461 , -0.5427, -0.3054, -0.4792],
[ 0.095 , -0.2701, -0.7071, -0.7739]]])
If a DataFrame or Panel contains homogeneously-typed data, the ndarray can actually be modified in-place, and the changes will be reflected in the data structure. For heterogeneous data (e.g. some of the DataFrame’s columns are not all the same dtype), this will not be the case. The values attribute itself, unlike the axis labels, cannot be assigned to.
Note
When working with heterogeneous data, the dtype of the resulting ndarray will be chosen to accommodate all of the data involved. For example, if strings are involved, the result will be of object dtype. If there are only floats and integers, the resulting array will be of float dtype.
Accelerated operations¶
pandas has support for accelerating certain types of binary numerical and boolean operations using
the numexpr
library 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 [14]: 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 [15]: df
Out[15]:
one two three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [16]: row = df.iloc[1]
In [17]: column = df['two']
In [18]: df.sub(row, axis='columns')
Out[18]:
one two three
a -0.924269 -1.362632 NaN
b 0.000000 0.000000 0.000000
c 0.639504 -2.973170 2.565487
d NaN -2.943392 -0.588625
In [19]: df.sub(row, axis=1)
Out[19]:
one two three
a -0.924269 -1.362632 NaN
b 0.000000 0.000000 0.000000
c 0.639504 -2.973170 2.565487
d NaN -2.943392 -0.588625
In [20]: df.sub(column, axis='index')
Out[20]:
one two three
a -2.226031 0.0 NaN
b -2.664393 0.0 -3.121397
c 0.948280 0.0 2.417260
d NaN 0.0 -0.766631
In [21]: df.sub(column, axis=0)
Out[21]:
one two three
a -2.226031 0.0 NaN
b -2.664393 0.0 -3.121397
c 0.948280 0.0 2.417260
d NaN 0.0 -0.766631
Furthermore you can align a level of a multi-indexed DataFrame with a Series.
In [22]: dfmi = df.copy()
In [23]: dfmi.index = pd.MultiIndex.from_tuples([(1,'a'),(1,'b'),(1,'c'),(2,'a')],
....: names=['first','second'])
....:
In [24]: dfmi.sub(column, axis=0, level='second')
Out[24]:
one two three
first second
1 a -2.226031 0.00000 NaN
b -2.664393 0.00000 -3.121397
c 0.948280 0.00000 2.417260
2 a NaN -1.58076 -2.347391
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 [25]: major_mean = wp.mean(axis='major')
In [26]: major_mean
Out[26]:
Item1 Item2
A -0.878036 -0.092218
B -0.060128 0.529811
C 0.099453 -0.715139
D 0.248599 -0.186535
In [27]: wp.sub(major_mean, axis='major')
Out[27]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
Minor_axis axis: A to D
And similarly for axis="items"
and axis="minor"
.
Note
I could be convinced to make the axis argument in the DataFrame methods match the broadcasting behavior of Panel. Though it would require a transition period so users can change their code…
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 [28]: s = pd.Series(np.arange(10))
In [29]: s
Out[29]:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
dtype: int64
In [30]: div, rem = divmod(s, 3)
In [31]: div
Out[31]:
0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
9 3
dtype: int64
In [32]: rem
Out[32]:
0 0
1 1
2 2
3 0
4 1
5 2
6 0
7 1
8 2
9 0
dtype: int64
In [33]: idx = pd.Index(np.arange(10))
In [34]: idx
Out[34]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')
In [35]: div, rem = divmod(idx, 3)
In [36]: div
Out[36]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2, 3], dtype='int64')
In [37]: rem
Out[37]: Int64Index([0, 1, 2, 0, 1, 2, 0, 1, 2, 0], dtype='int64')
We can also do elementwise divmod()
:
In [38]: div, rem = divmod(s, [2, 2, 3, 3, 4, 4, 5, 5, 6, 6])
In [39]: div
Out[39]:
0 0
1 0
2 0
3 1
4 1
5 1
6 1
7 1
8 1
9 1
dtype: int64
In [40]: rem
Out[40]:
0 0
1 1
2 2
3 0
4 0
5 1
6 1
7 2
8 2
9 3
dtype: int64
Missing data / operations with fill values¶
In Series and DataFrame, the arithmetic functions have the option of inputting
a fill_value, namely a value to substitute when at most one of the values at
a location are missing. For example, when adding two DataFrame objects, you may
wish to treat NaN as 0 unless both DataFrames are missing that value, in which
case the result will be NaN (you can later replace NaN with some other value
using fillna
if you wish).
In [41]: df
Out[41]:
one two three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [42]: df2
Out[42]:
one two three
a -1.101558 1.124472 1.000000
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [43]: df + df2
Out[43]:
one two three
a -2.203116 2.248945 NaN
b -0.354579 4.974208 -1.268586
c 0.924429 -0.972131 3.862388
d NaN -0.912575 -2.445837
In [44]: df.add(df2, fill_value=0)
Out[44]:
one two three
a -2.203116 2.248945 1.000000
b -0.354579 4.974208 -1.268586
c 0.924429 -0.972131 3.862388
d NaN -0.912575 -2.445837
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 [45]: df.gt(df2)
Out[45]:
one two three
a False False False
b False False False
c False False False
d False False False
In [46]: df2.ne(df)
Out[46]:
one two three
a False False True
b False False False
c False False False
d True False False
These operations produce a pandas object of the same type as the left-hand-side
input that is of dtype bool
. These boolean
objects can be used in
indexing operations, see the section on Boolean indexing.
Boolean Reductions¶
You can apply the reductions: empty
, any()
,
all()
, and bool()
to provide a
way to summarize a boolean result.
In [47]: (df > 0).all()
Out[47]:
one False
two False
three False
dtype: bool
In [48]: (df > 0).any()
Out[48]:
one True
two True
three True
dtype: bool
You can reduce to a final boolean value.
In [49]: (df > 0).any().any()
Out[49]: True
You can test if a pandas object is empty, via the empty
property.
In [50]: df.empty
Out[50]: False
In [51]: pd.DataFrame(columns=list('ABC')).empty
Out[51]: True
To evaluate single-element pandas objects in a boolean context, use the method
bool()
:
In [52]: pd.Series([True]).bool()
Out[52]: True
In [53]: pd.Series([False]).bool()
Out[53]: False
In [54]: pd.DataFrame([[True]]).bool()
Out[54]: True
In [55]: pd.DataFrame([[False]]).bool()
Out[55]: False
Warning
You might be tempted to do the following:
>>> if df:
...
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 [56]: df+df == df*2
Out[56]:
one two three
a True True False
b True True True
c True True True
d False True True
In [57]: (df+df == df*2).all()
Out[57]:
one False
two True
three False
dtype: bool
Notice that the boolean DataFrame df+df == df*2
contains some False values!
This is because NaNs do not compare as equals:
In [58]: np.nan == np.nan
Out[58]: 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 [59]: (df+df).equals(df*2)
Out[59]: True
Note that the Series or DataFrame index needs to be in the same order for equality to be True:
In [60]: df1 = pd.DataFrame({'col':['foo', 0, np.nan]})
In [61]: df2 = pd.DataFrame({'col':[np.nan, 0, 'foo']}, index=[2,1,0])
In [62]: df1.equals(df2)
Out[62]: False
In [63]: df1.equals(df2.sort_index())
Out[63]: True
Comparing array-like objects¶
You can conveniently perform element-wise comparisons when comparing a pandas data structure with a scalar value:
In [64]: pd.Series(['foo', 'bar', 'baz']) == 'foo'
Out[64]:
0 True
1 False
2 False
dtype: bool
In [65]: pd.Index(['foo', 'bar', 'baz']) == 'foo'
Out[65]: array([ True, False, False], dtype=bool)
Pandas also handles element-wise comparisons between different array-like objects of the same length:
In [66]: pd.Series(['foo', 'bar', 'baz']) == pd.Index(['foo', 'bar', 'qux'])
Out[66]:
0 True
1 True
2 False
dtype: bool
In [67]: pd.Series(['foo', 'bar', 'baz']) == np.array(['foo', 'bar', 'qux'])
Out[67]:
0 True
1 True
2 False
dtype: 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 compare
In [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 [68]: np.array([1, 2, 3]) == np.array([2])
Out[68]: array([False, True, False], dtype=bool)
or it can return False if broadcasting can not be done:
In [69]: np.array([1, 2, 3]) == np.array([1, 2])
Out[69]: 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 [70]: df1 = pd.DataFrame({'A' : [1., np.nan, 3., 5., np.nan],
....: 'B' : [np.nan, 2., 3., np.nan, 6.]})
....:
In [71]: df2 = pd.DataFrame({'A' : [5., 2., 4., np.nan, 3., 7.],
....: 'B' : [np.nan, np.nan, 3., 4., 6., 8.]})
....:
In [72]: df1
Out[72]:
A B
0 1.0 NaN
1 NaN 2.0
2 3.0 3.0
3 5.0 NaN
4 NaN 6.0
In [73]: df2
Out[73]:
A B
0 5.0 NaN
1 2.0 NaN
2 4.0 3.0
3 NaN 4.0
4 3.0 6.0
5 7.0 8.0
In [74]: df1.combine_first(df2)
Out[74]:
A B
0 1.0 NaN
1 2.0 2.0
2 3.0 3.0
3 5.0 4.0
4 3.0 6.0
5 7.0 8.0
General DataFrame Combine¶
The combine_first()
method above calls the more general
DataFrame.combine()
. This method takes another DataFrame
and a combiner function, aligns the input DataFrame and then passes the combiner
function pairs of Series (i.e., columns whose names are the same).
So, for instance, to reproduce combine_first()
as above:
In [75]: combiner = lambda x, y: np.where(pd.isna(x), y, x)
In [76]: df1.combine(df2, combiner)
Out[76]:
A B
0 1.0 NaN
1 2.0 2.0
2 3.0 3.0
3 5.0 4.0
4 3.0 6.0
5 7.0 8.0
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 [77]: df
Out[77]:
one two three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [78]: df.mean(0)
Out[78]:
one -0.272211
two 0.667306
three 0.024661
dtype: float64
In [79]: df.mean(1)
Out[79]:
a 0.011457
b 0.558507
c 0.635781
d -0.839603
dtype: float64
All such methods have a skipna
option signaling whether to exclude missing
data (True
by default):
In [80]: df.sum(0, skipna=False)
Out[80]:
one NaN
two 2.669223
three NaN
dtype: float64
In [81]: df.sum(axis=1, skipna=True)
Out[81]:
a 0.022914
b 1.675522
c 1.907343
d -1.679206
dtype: float64
Combined with the broadcasting / arithmetic behavior, one can describe various statistical procedures, like standardization (rendering data zero mean and standard deviation 1), very concisely:
In [82]: ts_stand = (df - df.mean()) / df.std()
In [83]: ts_stand.std()
Out[83]:
one 1.0
two 1.0
three 1.0
dtype: float64
In [84]: xs_stand = df.sub(df.mean(1), axis=0).div(df.std(1), axis=0)
In [85]: xs_stand.std(1)
Out[85]:
a 1.0
b 1.0
c 1.0
d 1.0
dtype: float64
Note that methods like cumsum()
and cumprod()
preserve the location of NaN
values. This is somewhat different from
expanding()
and rolling()
.
For more details please see this note.
In [86]: df.cumsum()
Out[86]:
one two three
a -1.101558 1.124472 NaN
b -1.278848 3.611576 -0.634293
c -0.816633 3.125511 1.296901
d NaN 2.669223 0.073983
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 [87]: np.mean(df['one'])
Out[87]: -0.27221094480450114
In [88]: np.mean(df['one'].values)
Out[88]: nan
Series.nunique()
will return the number of unique non-NA values in a
Series:
In [89]: series = pd.Series(np.random.randn(500))
In [90]: series[20:500] = np.nan
In [91]: series[10:20] = 5
In [92]: series.nunique()
Out[92]: 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 [93]: series = pd.Series(np.random.randn(1000))
In [94]: series[::2] = np.nan
In [95]: series.describe()
Out[95]:
count 500.000000
mean -0.032127
std 1.067484
min -3.463789
25% -0.725523
50% -0.053230
75% 0.679790
max 3.120271
dtype: float64
In [96]: frame = pd.DataFrame(np.random.randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])
In [97]: frame.iloc[::2] = np.nan
In [98]: frame.describe()
Out[98]:
a b c d e
count 500.000000 500.000000 500.000000 500.000000 500.000000
mean -0.045109 -0.052045 0.024520 0.006117 0.001141
std 1.029268 1.002320 1.042793 1.040134 1.005207
min -2.915767 -3.294023 -3.610499 -2.907036 -3.010899
25% -0.763783 -0.720389 -0.609600 -0.665896 -0.682900
50% -0.086033 -0.048843 0.006093 0.043191 -0.001651
75% 0.663399 0.620980 0.728382 0.735973 0.656439
max 3.400646 2.925597 3.416896 3.331522 3.007143
You can select specific percentiles to include in the output:
In [99]: series.describe(percentiles=[.05, .25, .75, .95])
Out[99]:
count 500.000000
mean -0.032127
std 1.067484
min -3.463789
5% -1.733545
25% -0.725523
50% -0.053230
75% 0.679790
95% 1.854383
max 3.120271
dtype: float64
By default, the median is always included.
For a non-numerical Series object, describe()
will give a simple
summary of the number of unique values and most frequently occurring values:
In [100]: s = pd.Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])
In [101]: s.describe()
Out[101]:
count 9
unique 4
top a
freq 5
dtype: object
Note that on a mixed-type DataFrame object, describe()
will
restrict the summary to include only numerical columns or, if none are, only
categorical columns:
In [102]: frame = pd.DataFrame({'a': ['Yes', 'Yes', 'No', 'No'], 'b': range(4)})
In [103]: frame.describe()
Out[103]:
b
count 4.000000
mean 1.500000
std 1.290994
min 0.000000
25% 0.750000
50% 1.500000
75% 2.250000
max 3.000000
This behaviour can be controlled by providing a list of types as include
/exclude
arguments. The special value all
can also be used:
In [104]: frame.describe(include=['object'])
Out[104]:
a
count 4
unique 2
top Yes
freq 2
In [105]: frame.describe(include=['number'])
Out[105]:
b
count 4.000000
mean 1.500000
std 1.290994
min 0.000000
25% 0.750000
50% 1.500000
75% 2.250000
max 3.000000
In [106]: frame.describe(include='all')
Out[106]:
a b
count 4 4.000000
unique 2 NaN
top Yes NaN
freq 2 NaN
mean NaN 1.500000
std NaN 1.290994
min NaN 0.000000
25% NaN 0.750000
50% NaN 1.500000
75% NaN 2.250000
max NaN 3.000000
That feature relies on select_dtypes. Refer to there for details about accepted inputs.
Index of Min/Max Values¶
The idxmin()
and idxmax()
functions on Series
and DataFrame compute the index labels with the minimum and maximum
corresponding values:
In [107]: s1 = pd.Series(np.random.randn(5))
In [108]: s1
Out[108]:
0 -1.649461
1 0.169660
2 1.246181
3 0.131682
4 -2.001988
dtype: float64
In [109]: s1.idxmin(), s1.idxmax()
Out[109]: (4, 2)
In [110]: df1 = pd.DataFrame(np.random.randn(5,3), columns=['A','B','C'])
In [111]: df1
Out[111]:
A B C
0 -1.273023 0.870502 0.214583
1 0.088452 -0.173364 1.207466
2 0.546121 0.409515 -0.310515
3 0.585014 -0.490528 -0.054639
4 -0.239226 0.701089 0.228656
In [112]: df1.idxmin(axis=0)
Out[112]:
A 0
B 3
C 2
dtype: int64
In [113]: df1.idxmax(axis=1)
Out[113]:
0 B
1 C
2 A
3 A
4 B
dtype: object
When there are multiple rows (or columns) matching the minimum or maximum
value, idxmin()
and idxmax()
return the first
matching index:
In [114]: df3 = pd.DataFrame([2, 1, 1, 3, np.nan], columns=['A'], index=list('edcba'))
In [115]: df3
Out[115]:
A
e 2.0
d 1.0
c 1.0
b 3.0
a NaN
In [116]: df3['A'].idxmin()
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 histogram
of a 1D array of values. It can also be used as a function on regular arrays:
In [117]: data = np.random.randint(0, 7, size=50)
In [118]: data
Out[118]:
array([3, 3, 0, 2, 1, 0, 5, 5, 3, 6, 1, 5, 6, 2, 0, 0, 6, 3, 3, 5, 0, 4, 3,
3, 3, 0, 6, 1, 3, 5, 5, 0, 4, 0, 6, 3, 6, 5, 4, 3, 2, 1, 5, 0, 1, 1,
6, 4, 1, 4])
In [119]: s = pd.Series(data)
In [120]: s.value_counts()
Out[120]:
3 11
0 9
5 8
6 7
1 7
4 5
2 3
dtype: int64
In [121]: pd.value_counts(data)
Out[121]:
3 11
0 9
5 8
6 7
1 7
4 5
2 3
dtype: int64
Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame:
In [122]: s5 = pd.Series([1, 1, 3, 3, 3, 5, 5, 7, 7, 7])
In [123]: s5.mode()
Out[123]:
0 3
1 7
dtype: int64
In [124]: df5 = pd.DataFrame({"A": np.random.randint(0, 7, size=50),
.....: "B": np.random.randint(-10, 15, size=50)})
.....:
In [125]: df5.mode()
Out[125]:
A B
0 2 -5
Discretization and quantiling¶
Continuous values can be discretized using the cut()
(bins based on values)
and qcut()
(bins based on sample quantiles) functions:
In [126]: arr = np.random.randn(20)
In [127]: factor = pd.cut(arr, 4)
In [128]: factor
Out[128]:
[(-2.611, -1.58], (0.473, 1.499], (-2.611, -1.58], (-1.58, -0.554], (-0.554, 0.473], ..., (0.473, 1.499], (0.473, 1.499], (-0.554, 0.473], (-0.554, 0.473], (-0.554, 0.473]]
Length: 20
Categories (4, interval[float64]): [(-2.611, -1.58] < (-1.58, -0.554] < (-0.554, 0.473] <
(0.473, 1.499]]
In [129]: factor = pd.cut(arr, [-5, -1, 0, 1, 5])
In [130]: factor
Out[130]:
[(-5, -1], (0, 1], (-5, -1], (-1, 0], (-1, 0], ..., (1, 5], (1, 5], (-1, 0], (-1, 0], (-1, 0]]
Length: 20
Categories (4, interval[int64]): [(-5, -1] < (-1, 0] < (0, 1] < (1, 5]]
qcut()
computes sample quantiles. For example, we could slice up some
normally distributed data into equal-size quartiles like so:
In [131]: arr = np.random.randn(30)
In [132]: factor = pd.qcut(arr, [0, .25, .5, .75, 1])
In [133]: factor
Out[133]:
[(0.544, 1.976], (0.544, 1.976], (-1.255, -0.375], (0.544, 1.976], (-0.103, 0.544], ..., (-0.103, 0.544], (0.544, 1.976], (-0.103, 0.544], (-1.255, -0.375], (-0.375, -0.103]]
Length: 30
Categories (4, interval[float64]): [(-1.255, -0.375] < (-0.375, -0.103] < (-0.103, 0.544] <
(0.544, 1.976]]
In [134]: pd.value_counts(factor)
Out[134]:
(0.544, 1.976] 8
(-1.255, -0.375] 8
(-0.103, 0.544] 7
(-0.375, -0.103] 7
dtype: int64
We can also pass infinite values to define the bins:
In [135]: arr = np.random.randn(20)
In [136]: factor = pd.cut(arr, [-np.inf, 0, np.inf])
In [137]: factor
Out[137]:
[(0.0, inf], (0.0, inf], (0.0, inf], (0.0, inf], (-inf, 0.0], ..., (-inf, 0.0], (-inf, 0.0], (0.0, inf], (-inf, 0.0], (0.0, inf]]
Length: 20
Categories (2, interval[float64]): [(-inf, 0.0] < (0.0, inf]]
Function application¶
To apply your own or another library’s functions to pandas objects,
you should be aware of the three methods below. The appropriate
method to use depends on whether your function expects to operate
on an entire DataFrame
or Series
, row- or column-wise, or elementwise.
- Tablewise Function Application:
pipe()
- Row or Column-wise Function Application:
apply()
- Aggregation API:
agg()
andtransform()
- 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 [138]: import statsmodels.formula.api as sm
In [139]: bb = pd.read_csv('data/baseball.csv', index_col='id')
In [140]: (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[140]:
<class 'statsmodels.iolib.summary.Summary'>
"""
OLS Regression Results
==============================================================================
Dep. Variable: hr R-squared: 0.685
Model: OLS Adj. R-squared: 0.665
Method: Least Squares F-statistic: 34.28
Date: Tue, 12 Jun 2018 Prob (F-statistic): 3.48e-15
Time: 12:53:14 Log-Likelihood: -205.92
No. Observations: 68 AIC: 421.8
Df Residuals: 63 BIC: 432.9
Df Model: 4
Covariance 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.780
C(lg)[T.NL] -2.2736 1.325 -1.716 0.091 -4.922 0.375
ln_h -1.3542 0.875 -1.547 0.127 -3.103 0.395
year 4.2277 2.324 1.819 0.074 -0.417 8.872
g 0.1841 0.029 6.258 0.000 0.125 0.243
==============================================================================
Omnibus: 10.875 Durbin-Watson: 1.999
Prob(Omnibus): 0.004 Jarque-Bera (JB): 17.298
Skew: 0.537 Prob(JB): 0.000175
Kurtosis: 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 are
strong 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 [141]: df.apply(np.mean)
Out[141]:
one -0.272211
two 0.667306
three 0.024661
dtype: float64
In [142]: df.apply(np.mean, axis=1)
Out[142]:
a 0.011457
b 0.558507
c 0.635781
d -0.839603
dtype: float64
In [143]: df.apply(lambda x: x.max() - x.min())
Out[143]:
one 1.563773
two 2.973170
three 3.154112
dtype: float64
In [144]: df.apply(np.cumsum)
Out[144]:
one two three
a -1.101558 1.124472 NaN
b -1.278848 3.611576 -0.634293
c -0.816633 3.125511 1.296901
d NaN 2.669223 0.073983
In [145]: df.apply(np.exp)
Out[145]:
one two three
a 0.332353 3.078592 NaN
b 0.837537 12.026397 0.53031
c 1.587586 0.615041 6.89774
d NaN 0.633631 0.29437
The apply()
method will also dispatch on a string method name.
In [146]: df.apply('mean')
Out[146]:
one -0.272211
two 0.667306
three 0.024661
dtype: float64
In [147]: df.apply('mean', axis=1)
Out[147]:
a 0.011457
b 0.558507
c 0.635781
d -0.839603
dtype: float64
The return type of the function passed to apply()
affects the
type of the final output from DataFrame.apply
for the default behaviour:
- If the applied function returns a
Series
, the final output is aDataFrame
. The columns match the index of theSeries
returned by the applied function. - If the applied function returns any other type, the final output is a
Series
.
This default behaviour can be overridden using the result_type
, which
accepts three options: reduce
, broadcast
, and expand
.
These will determine how list-likes return values expand (or not) to a DataFrame
.
apply()
combined with some cleverness can be used to answer many questions
about a data set. For example, suppose we wanted to extract the date where the
maximum value for each column occurred:
In [148]: tsdf = pd.DataFrame(np.random.randn(1000, 3), columns=['A', 'B', 'C'],
.....: index=pd.date_range('1/1/2000', periods=1000))
.....:
In [149]: tsdf.apply(lambda x: x.idxmax())
Out[149]:
A 2001-04-25
B 2002-05-31
C 2002-09-25
dtype: datetime64[ns]
You may also pass additional arguments and keyword arguments to the apply()
method. For instance, consider the following function you would like to apply:
def subtract_and_divide(x, sub, divide=1):
return (x - sub) / divide
You may then apply this function as follows:
df.apply(subtract_and_divide, args=(5,), divide=3)
Another useful feature is the ability to pass Series methods to carry out some Series operation on each column or row:
In [150]: tsdf
Out[150]:
A B C
2000-01-01 -0.720299 0.546303 -0.082042
2000-01-02 0.200295 -0.577554 -0.908402
2000-01-03 0.102533 1.653614 0.303319
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 0.532566 0.341548 0.150493
2000-01-09 0.330418 1.761200 0.567133
2000-01-10 -0.251020 1.020099 1.893177
In [151]: tsdf.apply(pd.Series.interpolate)
Out[151]:
A B C
2000-01-01 -0.720299 0.546303 -0.082042
2000-01-02 0.200295 -0.577554 -0.908402
2000-01-03 0.102533 1.653614 0.303319
2000-01-04 0.188539 1.391201 0.272754
2000-01-05 0.274546 1.128788 0.242189
2000-01-06 0.360553 0.866374 0.211624
2000-01-07 0.446559 0.603961 0.181059
2000-01-08 0.532566 0.341548 0.150493
2000-01-09 0.330418 1.761200 0.567133
2000-01-10 -0.251020 1.020099 1.893177
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 [152]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],
.....: index=pd.date_range('1/1/2000', periods=10))
.....:
In [153]: tsdf.iloc[3:7] = np.nan
In [154]: tsdf
Out[154]:
A B C
2000-01-01 0.170247 -0.916844 0.835024
2000-01-02 1.259919 0.801111 0.445614
2000-01-03 1.453046 2.430373 0.653093
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 -1.874526 0.569822 -0.609644
2000-01-09 0.812462 0.565894 -1.461363
2000-01-10 -0.985475 1.388154 -0.078747
Using a single function is equivalent to apply()
. You can also
pass named methods as strings. These will return a Series
of the aggregated
output:
In [155]: tsdf.agg(np.sum)
Out[155]:
A 0.835673
B 4.838510
C -0.216025
dtype: float64
In [156]: tsdf.agg('sum')
Out[156]:
A 0.835673
B 4.838510
C -0.216025
dtype: float64
# these are equivalent to a ``.sum()`` because we are aggregating on a single function
In [157]: tsdf.sum()
Out[157]:
A 0.835673
B 4.838510
C -0.216025
dtype: float64
Single aggregations on a Series
this will return a scalar value:
In [158]: tsdf.A.agg('sum')
Out[158]: 0.83567297915820504
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 [159]: tsdf.agg(['sum'])
Out[159]:
A B C
sum 0.835673 4.83851 -0.216025
Multiple functions yield multiple rows:
In [160]: tsdf.agg(['sum', 'mean'])
Out[160]:
A B C
sum 0.835673 4.838510 -0.216025
mean 0.139279 0.806418 -0.036004
On a Series
, multiple functions return a Series
, indexed by the function names:
In [161]: tsdf.A.agg(['sum', 'mean'])
Out[161]:
sum 0.835673
mean 0.139279
Name: A, dtype: float64
Passing a lambda
function will yield a <lambda>
named row:
In [162]: tsdf.A.agg(['sum', lambda x: x.mean()])
Out[162]:
sum 0.835673
<lambda> 0.139279
Name: A, dtype: float64
Passing a named function will yield that name for the row:
In [163]: def mymean(x):
.....: return x.mean()
.....:
In [164]: tsdf.A.agg(['sum', mymean])
Out[164]:
sum 0.835673
mymean 0.139279
Name: A, dtype: float64
Aggregating with a dict¶
Passing a dictionary of column names to a scalar or a list of scalars, to DataFrame.agg
allows you to customize which functions are applied to which columns. Note that the results
are not in any particular order, you can use an OrderedDict
instead to guarantee ordering.
In [165]: tsdf.agg({'A': 'mean', 'B': 'sum'})
Out[165]:
A 0.139279
B 4.838510
dtype: float64
Passing a list-like will generate a DataFrame
output. You will get a matrix-like output
of all of the aggregators. The output will consist of all unique functions. Those that are
not noted for a particular column will be NaN
:
In [166]: tsdf.agg({'A': ['mean', 'min'], 'B': 'sum'})
Out[166]:
A B
mean 0.139279 NaN
min -1.874526 NaN
sum NaN 4.83851
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 [167]: mdf = pd.DataFrame({'A': [1, 2, 3],
.....: 'B': [1., 2., 3.],
.....: 'C': ['foo', 'bar', 'baz'],
.....: 'D': pd.date_range('20130101', periods=3)})
.....:
In [168]: mdf.dtypes
Out[168]:
A int64
B float64
C object
D datetime64[ns]
dtype: object
In [169]: mdf.agg(['min', 'sum'])
Out[169]:
A B C D
min 1 1.0 bar 2013-01-01
sum 6 6.0 foobarbaz NaT
Custom describe¶
With .agg()
is it possible to easily create a custom describe function, similar
to the built in describe function.
In [170]: from functools import partial
In [171]: q_25 = partial(pd.Series.quantile, q=0.25)
In [172]: q_25.__name__ = '25%'
In [173]: q_75 = partial(pd.Series.quantile, q=0.75)
In [174]: q_75.__name__ = '75%'
In [175]: tsdf.agg(['count', 'mean', 'std', 'min', q_25, 'median', q_75, 'max'])
Out[175]:
A B C
count 6.000000 6.000000 6.000000
mean 0.139279 0.806418 -0.036004
std 1.323362 1.100830 0.874990
min -1.874526 -0.916844 -1.461363
25% -0.696544 0.566876 -0.476920
median 0.491354 0.685467 0.183433
75% 1.148055 1.241393 0.601223
max 1.453046 2.430373 0.835024
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 [176]: tsdf = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'],
.....: index=pd.date_range('1/1/2000', periods=10))
.....:
In [177]: tsdf.iloc[3:7] = np.nan
In [178]: tsdf
Out[178]:
A B C
2000-01-01 -0.578465 -0.503335 -0.987140
2000-01-02 -0.767147 -0.266046 1.083797
2000-01-03 0.195348 0.722247 -0.894537
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 -0.556397 0.542165 -0.308675
2000-01-09 -1.010924 -0.672504 -1.139222
2000-01-10 0.354653 0.563622 -0.365106
Transform the entire frame. .transform()
allows input functions as: a NumPy function, a string
function name or a user defined function.
In [179]: tsdf.transform(np.abs)
Out[179]:
A B C
2000-01-01 0.578465 0.503335 0.987140
2000-01-02 0.767147 0.266046 1.083797
2000-01-03 0.195348 0.722247 0.894537
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 0.556397 0.542165 0.308675
2000-01-09 1.010924 0.672504 1.139222
2000-01-10 0.354653 0.563622 0.365106
In [180]: tsdf.transform('abs')
Out[180]:
A B C
2000-01-01 0.578465 0.503335 0.987140
2000-01-02 0.767147 0.266046 1.083797
2000-01-03 0.195348 0.722247 0.894537
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 0.556397 0.542165 0.308675
2000-01-09 1.010924 0.672504 1.139222
2000-01-10 0.354653 0.563622 0.365106
In [181]: tsdf.transform(lambda x: x.abs())
Out[181]:
A B C
2000-01-01 0.578465 0.503335 0.987140
2000-01-02 0.767147 0.266046 1.083797
2000-01-03 0.195348 0.722247 0.894537
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 0.556397 0.542165 0.308675
2000-01-09 1.010924 0.672504 1.139222
2000-01-10 0.354653 0.563622 0.365106
Here transform()
received a single function; this is equivalent to a ufunc application.
In [182]: np.abs(tsdf)
Out[182]:
A B C
2000-01-01 0.578465 0.503335 0.987140
2000-01-02 0.767147 0.266046 1.083797
2000-01-03 0.195348 0.722247 0.894537
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 0.556397 0.542165 0.308675
2000-01-09 1.010924 0.672504 1.139222
2000-01-10 0.354653 0.563622 0.365106
Passing a single function to .transform()
with a Series
will yield a single Series
in return.
In [183]: tsdf.A.transform(np.abs)
Out[183]:
2000-01-01 0.578465
2000-01-02 0.767147
2000-01-03 0.195348
2000-01-04 NaN
2000-01-05 NaN
2000-01-06 NaN
2000-01-07 NaN
2000-01-08 0.556397
2000-01-09 1.010924
2000-01-10 0.354653
Freq: D, Name: A, dtype: float64
Transform with multiple functions¶
Passing multiple functions will yield a column multi-indexed DataFrame. The first level will be the original frame column names; the second level will be the names of the transforming functions.
In [184]: tsdf.transform([np.abs, lambda x: x+1])
Out[184]:
A B C
absolute <lambda> absolute <lambda> absolute <lambda>
2000-01-01 0.578465 0.421535 0.503335 0.496665 0.987140 0.012860
2000-01-02 0.767147 0.232853 0.266046 0.733954 1.083797 2.083797
2000-01-03 0.195348 1.195348 0.722247 1.722247 0.894537 0.105463
2000-01-04 NaN NaN NaN NaN NaN NaN
2000-01-05 NaN NaN NaN NaN NaN NaN
2000-01-06 NaN NaN NaN NaN NaN NaN
2000-01-07 NaN NaN NaN NaN NaN NaN
2000-01-08 0.556397 0.443603 0.542165 1.542165 0.308675 0.691325
2000-01-09 1.010924 -0.010924 0.672504 0.327496 1.139222 -0.139222
2000-01-10 0.354653 1.354653 0.563622 1.563622 0.365106 0.634894
Passing multiple functions to a Series will yield a DataFrame. The resulting column names will be the transforming functions.
In [185]: tsdf.A.transform([np.abs, lambda x: x+1])
Out[185]:
absolute <lambda>
2000-01-01 0.578465 0.421535
2000-01-02 0.767147 0.232853
2000-01-03 0.195348 1.195348
2000-01-04 NaN NaN
2000-01-05 NaN NaN
2000-01-06 NaN NaN
2000-01-07 NaN NaN
2000-01-08 0.556397 0.443603
2000-01-09 1.010924 -0.010924
2000-01-10 0.354653 1.354653
Transforming with a dict¶
Passing a dict of functions will allow selective transforming per column.
In [186]: tsdf.transform({'A': np.abs, 'B': lambda x: x+1})
Out[186]:
A B
2000-01-01 0.578465 0.496665
2000-01-02 0.767147 0.733954
2000-01-03 0.195348 1.722247
2000-01-04 NaN NaN
2000-01-05 NaN NaN
2000-01-06 NaN NaN
2000-01-07 NaN NaN
2000-01-08 0.556397 1.542165
2000-01-09 1.010924 0.327496
2000-01-10 0.354653 1.563622
Passing a dict of lists will generate a multi-indexed DataFrame with these selective transforms.
In [187]: tsdf.transform({'A': np.abs, 'B': [lambda x: x+1, 'sqrt']})
Out[187]:
A B
absolute <lambda> sqrt
2000-01-01 0.578465 0.496665 NaN
2000-01-02 0.767147 0.733954 NaN
2000-01-03 0.195348 1.722247 0.849851
2000-01-04 NaN NaN NaN
2000-01-05 NaN NaN NaN
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-08 0.556397 1.542165 0.736318
2000-01-09 1.010924 0.327496 NaN
2000-01-10 0.354653 1.563622 0.750748
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 [188]: df4
Out[188]:
one two three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [189]: f = lambda x: len(str(x))
In [190]: df4['one'].map(f)
Out[190]:
a 19
b 20
c 18
d 3
Name: one, dtype: int64
In [191]: df4.applymap(f)
Out[191]:
one two three
a 19 18 3
b 20 18 19
c 18 20 18
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 related
to merging/joining functionality:
In [192]: s = pd.Series(['six', 'seven', 'six', 'seven', 'six'],
.....: index=['a', 'b', 'c', 'd', 'e'])
.....:
In [193]: t = pd.Series({'six' : 6., 'seven' : 7.})
In [194]: s
Out[194]:
a six
b seven
c six
d seven
e six
dtype: object
In [195]: s.map(t)
Out[195]:
a 6.0
b 7.0
c 6.0
d 7.0
e 6.0
dtype: float64
Applying with a Panel¶
Applying with a Panel
will pass a Series
to the applied function. If the applied
function returns a Series
, the result of the application will be a Panel
. If the applied function
reduces to a scalar, the result of the application will be a DataFrame
.
In [196]: import pandas.util.testing as tm
In [197]: panel = tm.makePanel(5)
In [198]: panel
Out[198]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
Minor_axis axis: A to D
In [199]: panel['ItemA']
Out[199]:
A B C D
2000-01-03 1.092702 0.604244 -2.927808 0.339642
2000-01-04 -1.481449 -0.487265 0.082065 1.499953
2000-01-05 1.781190 1.990533 0.456554 -0.317818
2000-01-06 -0.031543 0.327007 -1.757911 0.447371
2000-01-07 0.480993 1.053639 0.982407 -1.315799
A transformational apply.
In [200]: result = panel.apply(lambda x: x*2, axis='items')
In [201]: result
Out[201]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
Minor_axis axis: A to D
In [202]: result['ItemA']
Out[202]:
A B C D
2000-01-03 2.185405 1.208489 -5.855616 0.679285
2000-01-04 -2.962899 -0.974530 0.164130 2.999905
2000-01-05 3.562379 3.981066 0.913107 -0.635635
2000-01-06 -0.063086 0.654013 -3.515821 0.894742
2000-01-07 0.961986 2.107278 1.964815 -2.631598
A reduction operation.
In [203]: panel.apply(lambda x: x.dtype, axis='items')
Out[203]:
A B C D
2000-01-03 float64 float64 float64 float64
2000-01-04 float64 float64 float64 float64
2000-01-05 float64 float64 float64 float64
2000-01-06 float64 float64 float64 float64
2000-01-07 float64 float64 float64 float64
A similar reduction type operation.
In [204]: panel.apply(lambda x: x.sum(), axis='major_axis')
Out[204]:
ItemA ItemB ItemC
A 1.841893 0.918017 -1.160547
B 3.488158 -2.629773 0.603397
C -3.164692 0.805970 0.806501
D 0.653349 -0.152299 0.252577
This last reduction is equivalent to:
In [205]: panel.sum('major_axis')
Out[205]:
ItemA ItemB ItemC
A 1.841893 0.918017 -1.160547
B 3.488158 -2.629773 0.603397
C -3.164692 0.805970 0.806501
D 0.653349 -0.152299 0.252577
A transformation operation that returns a Panel
, but is computing
the z-score across the major_axis
.
In [206]: result = panel.apply(
.....: lambda x: (x-x.mean())/x.std(),
.....: axis='major_axis')
.....:
In [207]: result
Out[207]:
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
Minor_axis axis: A to D
In [208]: result['ItemA']
Out[208]:
A B C D
2000-01-03 0.585813 -0.102070 -1.394063 0.201263
2000-01-04 -1.496089 -1.295066 0.434343 1.318766
2000-01-05 1.142642 1.413112 0.661833 -0.431942
2000-01-06 -0.323445 -0.405085 -0.683386 0.305017
2000-01-07 0.091079 0.389108 0.981273 -1.393105
Apply can also accept multiple axes in the axis
argument. This will pass a
DataFrame
of the cross-section to the applied function.
In [209]: f = lambda x: ((x.T-x.mean(1))/x.std(1)).T
In [210]: result = panel.apply(f, axis = ['items','major_axis'])
In [211]: result
Out[211]:
<class 'pandas.core.panel.Panel'>
Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
Items axis: A to D
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
Minor_axis axis: ItemA to ItemC
In [212]: result.loc[:,:,'ItemA']
Out[212]:
A B C D
2000-01-03 0.859304 0.448509 -1.109374 0.397237
2000-01-04 -1.053319 -1.063370 0.986639 1.152266
2000-01-05 1.106511 1.143185 -0.093917 -0.583083
2000-01-06 0.561619 -0.835608 -1.075936 0.194525
2000-01-07 -0.339514 1.097901 0.747522 -1.147605
This is equivalent to the following:
In [213]: result = pd.Panel(dict([ (ax, f(panel.loc[:,:,ax]))
.....: for ax in panel.minor_axis ]))
.....:
In [214]: result
Out[214]:
<class 'pandas.core.panel.Panel'>
Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
Items axis: A to D
Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
Minor_axis axis: ItemA to ItemC
In [215]: result.loc[:,:,'ItemA']
Out[215]:
A B C D
2000-01-03 0.859304 0.448509 -1.109374 0.397237
2000-01-04 -1.053319 -1.063370 0.986639 1.152266
2000-01-05 1.106511 1.143185 -0.093917 -0.583083
2000-01-06 0.561619 -0.835608 -1.075936 0.194525
2000-01-07 -0.339514 1.097901 0.747522 -1.147605
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 [216]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [217]: s
Out[217]:
a -0.454087
b -0.360309
c -0.951631
d -0.535459
e 0.835231
dtype: float64
In [218]: s.reindex(['e', 'b', 'f', 'd'])
Out[218]:
e 0.835231
b -0.360309
f NaN
d -0.535459
dtype: float64
Here, the f
label was not contained in the Series and hence appears as
NaN
in the result.
With a DataFrame, you can simultaneously reindex the index and columns:
In [219]: df
Out[219]:
one two three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [220]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
Out[220]:
three two one
c 1.931194 -0.486066 0.462215
f NaN NaN NaN
b -0.634293 2.487104 -0.177289
You may also use reindex
with an axis
keyword:
In [221]: df.reindex(['c', 'f', 'b'], axis='index')
Out[221]:
one two three
c 0.462215 -0.486066 1.931194
f NaN NaN NaN
b -0.177289 2.487104 -0.634293
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 [222]: rs = s.reindex(df.index)
In [223]: rs
Out[223]:
a -0.454087
b -0.360309
c -0.951631
d -0.535459
dtype: float64
In [224]: rs.index is df.index
Out[224]: 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 [225]: df.reindex(['c', 'f', 'b'], axis='index')
Out[225]:
one two three
c 0.462215 -0.486066 1.931194
f NaN NaN NaN
b -0.177289 2.487104 -0.634293
In [226]: df.reindex(['three', 'two', 'one'], axis='columns')
Out[226]:
three two one
a NaN 1.124472 -1.101558
b -0.634293 2.487104 -0.177289
c 1.931194 -0.486066 0.462215
d -1.222918 -0.456288 NaN
See also
MultiIndex / Advanced Indexing is an even more concise way of doing reindexing.
Note
When writing performance-sensitive code, there is a good reason to spend
some time becoming a reindexing ninja: many operations are faster on
pre-aligned data. Adding two unaligned DataFrames internally triggers a
reindexing step. For exploratory analysis you will hardly notice the
difference (because reindex
has been heavily optimized), but when CPU
cycles matter sprinkling a few explicit reindex
calls here and there can
have an impact.
Reindexing to align with another object¶
You may wish to take an object and reindex its axes to be labeled the same as
another object. While the syntax for this is straightforward albeit verbose, it
is a common enough operation that the reindex_like()
method is
available to make this simpler:
In [227]: df2
Out[227]:
one two
a -1.101558 1.124472
b -0.177289 2.487104
c 0.462215 -0.486066
In [228]: df3
Out[228]:
one two
a -0.829347 0.082635
b 0.094922 1.445267
c 0.734426 -1.527903
In [229]: df.reindex_like(df2)
Out[229]:
one two
a -1.101558 1.124472
b -0.177289 2.487104
c 0.462215 -0.486066
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 [230]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [231]: s1 = s[:4]
In [232]: s2 = s[1:]
In [233]: s1.align(s2)
Out[233]:
(a 0.505453
b 1.788110
c -0.405908
d -0.801912
e NaN
dtype: float64, a NaN
b 1.788110
c -0.405908
d -0.801912
e 0.768460
dtype: float64)
In [234]: s1.align(s2, join='inner')
Out[234]:
(b 1.788110
c -0.405908
d -0.801912
dtype: float64, b 1.788110
c -0.405908
d -0.801912
dtype: float64)
In [235]: s1.align(s2, join='left')
Out[235]:
(a 0.505453
b 1.788110
c -0.405908
d -0.801912
dtype: float64, a NaN
b 1.788110
c -0.405908
d -0.801912
dtype: float64)
For DataFrames, the join method will be applied to both the index and the columns by default:
In [236]: df.align(df2, join='inner')
Out[236]:
( one two
a -1.101558 1.124472
b -0.177289 2.487104
c 0.462215 -0.486066, one two
a -1.101558 1.124472
b -0.177289 2.487104
c 0.462215 -0.486066)
You can also pass an axis
option to only align on the specified axis:
In [237]: df.align(df2, join='inner', axis=0)
Out[237]:
( one two three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194, one two
a -1.101558 1.124472
b -0.177289 2.487104
c 0.462215 -0.486066)
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 [238]: df.align(df2.iloc[0], axis=1)
Out[238]:
( one three two
a -1.101558 NaN 1.124472
b -0.177289 -0.634293 2.487104
c 0.462215 1.931194 -0.486066
d NaN -1.222918 -0.456288, one -1.101558
three NaN
two 1.124472
Name: a, dtype: float64)
Filling while reindexing¶
reindex()
takes an optional parameter method
which is a
filling method chosen from the following table:
Method | Action |
---|---|
pad / ffill | Fill values forward |
bfill / backfill | Fill values backward |
nearest | Fill from the nearest index value |
We illustrate these fill methods on a simple Series:
In [239]: rng = pd.date_range('1/3/2000', periods=8)
In [240]: ts = pd.Series(np.random.randn(8), index=rng)
In [241]: ts2 = ts[[0, 3, 6]]
In [242]: ts
Out[242]:
2000-01-03 0.466284
2000-01-04 -0.457411
2000-01-05 -0.364060
2000-01-06 0.785367
2000-01-07 -1.463093
2000-01-08 1.187315
2000-01-09 -0.493153
2000-01-10 -1.323445
Freq: D, dtype: float64
In [243]: ts2
Out[243]:
2000-01-03 0.466284
2000-01-06 0.785367
2000-01-09 -0.493153
dtype: float64
In [244]: ts2.reindex(ts.index)
Out[244]:
2000-01-03 0.466284
2000-01-04 NaN
2000-01-05 NaN
2000-01-06 0.785367
2000-01-07 NaN
2000-01-08 NaN
2000-01-09 -0.493153
2000-01-10 NaN
Freq: D, dtype: float64
In [245]: ts2.reindex(ts.index, method='ffill')
Out[245]:
2000-01-03 0.466284
2000-01-04 0.466284
2000-01-05 0.466284
2000-01-06 0.785367
2000-01-07 0.785367
2000-01-08 0.785367
2000-01-09 -0.493153
2000-01-10 -0.493153
Freq: D, dtype: float64
In [246]: ts2.reindex(ts.index, method='bfill')
Out[246]:
2000-01-03 0.466284
2000-01-04 0.785367
2000-01-05 0.785367
2000-01-06 0.785367
2000-01-07 -0.493153
2000-01-08 -0.493153
2000-01-09 -0.493153
2000-01-10 NaN
Freq: D, dtype: float64
In [247]: ts2.reindex(ts.index, method='nearest')
Out[247]:
2000-01-03 0.466284
2000-01-04 0.466284
2000-01-05 0.785367
2000-01-06 0.785367
2000-01-07 0.785367
2000-01-08 -0.493153
2000-01-09 -0.493153
2000-01-10 -0.493153
Freq: D, dtype: float64
These methods require that the indexes are ordered increasing or decreasing.
Note that the same result could have been achieved using
fillna (except for method='nearest'
) or
interpolate:
In [248]: ts2.reindex(ts.index).fillna(method='ffill')
Out[248]:
2000-01-03 0.466284
2000-01-04 0.466284
2000-01-05 0.466284
2000-01-06 0.785367
2000-01-07 0.785367
2000-01-08 0.785367
2000-01-09 -0.493153
2000-01-10 -0.493153
Freq: D, dtype: float64
reindex()
will raise a ValueError if the index is not monotonically
increasing or decreasing. fillna()
and interpolate()
will not perform any checks on the order of the index.
Limits on filling while reindexing¶
The limit
and tolerance
arguments provide additional control over
filling while reindexing. Limit specifies the maximum count of consecutive
matches:
In [249]: ts2.reindex(ts.index, method='ffill', limit=1)
Out[249]:
2000-01-03 0.466284
2000-01-04 0.466284
2000-01-05 NaN
2000-01-06 0.785367
2000-01-07 0.785367
2000-01-08 NaN
2000-01-09 -0.493153
2000-01-10 -0.493153
Freq: D, dtype: float64
In contrast, tolerance specifies the maximum distance between the index and indexer values:
In [250]: ts2.reindex(ts.index, method='ffill', tolerance='1 day')
Out[250]:
2000-01-03 0.466284
2000-01-04 0.466284
2000-01-05 NaN
2000-01-06 0.785367
2000-01-07 0.785367
2000-01-08 NaN
2000-01-09 -0.493153
2000-01-10 -0.493153
Freq: D, dtype: float64
Notice that when used on a DatetimeIndex
, TimedeltaIndex
or
PeriodIndex
, tolerance
will coerced into a Timedelta
if possible.
This allows you to specify tolerance with appropriate strings.
Dropping labels from an axis¶
A method closely related to reindex
is the drop()
function.
It removes a set of labels from an axis:
In [251]: df
Out[251]:
one two three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [252]: df.drop(['a', 'd'], axis=0)
Out[252]:
one two three
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
In [253]: df.drop(['one'], axis=1)
Out[253]:
two three
a 1.124472 NaN
b 2.487104 -0.634293
c -0.486066 1.931194
d -0.456288 -1.222918
Note that the following also works, but is a bit less obvious / clean:
In [254]: df.reindex(df.index.difference(['a', 'd']))
Out[254]:
one two three
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
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 [255]: s
Out[255]:
a 0.505453
b 1.788110
c -0.405908
d -0.801912
e 0.768460
dtype: float64
In [256]: s.rename(str.upper)
Out[256]:
A 0.505453
B 1.788110
C -0.405908
D -0.801912
E 0.768460
dtype: float64
If you pass a function, it must return a value when called with any of the labels (and must produce a set of unique values). A dict or Series can also be used:
In [257]: df.rename(columns={'one': 'foo', 'two': 'bar'},
.....: index={'a': 'apple', 'b': 'banana', 'd': 'durian'})
.....:
Out[257]:
foo bar three
apple -1.101558 1.124472 NaN
banana -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
durian NaN -0.456288 -1.222918
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 [258]: df.rename({'one': 'foo', 'two': 'bar'}, axis='columns')
Out[258]:
foo bar three
a -1.101558 1.124472 NaN
b -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
d NaN -0.456288 -1.222918
In [259]: df.rename({'a': 'apple', 'b': 'banana', 'd': 'durian'}, axis='index')
Out[259]:
one two three
apple -1.101558 1.124472 NaN
banana -0.177289 2.487104 -0.634293
c 0.462215 -0.486066 1.931194
durian NaN -0.456288 -1.222918
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 [260]: s.rename("scalar-name")
Out[260]:
a 0.505453
b 1.788110
c -0.405908
d -0.801912
e 0.768460
Name: scalar-name, dtype: float64
The Panel class has a related rename_axis()
class which can rename
any of its three axes.
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 [261]: df = pd.DataFrame({'col1' : np.random.randn(3), 'col2' : np.random.randn(3)},
.....: index=['a', 'b', 'c'])
.....:
In [262]: for col in df:
.....: print(col)
.....:
col1
col2
Pandas objects also have the dict-like iteritems()
method to
iterate over the (key, value) pairs.
To iterate over the rows of a DataFrame, you can use the following methods:
iterrows()
: Iterate over the rows of a DataFrame as (index, Series) pairs. This converts the rows to Series objects, which can change the dtypes and has some performance implications.itertuples()
: Iterate over the rows of a DataFrame as namedtuples of the values. This is a lot faster thaniterrows()
, and is in most cases preferable to use to 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 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
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 [263]: df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c']})
In [264]: for index, row in df.iterrows():
.....: row['a'] = 10
.....:
In [265]: df
Out[265]:
a b
0 1 a
1 2 b
2 3 c
iteritems¶
Consistent with the dict-like interface, iteritems()
iterates
through key-value pairs:
- Series: (index, scalar value) pairs
- DataFrame: (column, Series) pairs
- Panel: (item, DataFrame) pairs
For example:
In [266]: for item, frame in wp.iteritems():
.....: print(item)
.....: print(frame)
.....:
Item1
A B C D
2000-01-01 -0.433567 -0.273610 0.680433 -0.308450
2000-01-02 -0.276099 -1.821168 -1.993606 -1.927385
2000-01-03 -2.027924 1.624972 0.551135 3.059267
2000-01-04 0.455264 -0.030740 0.935716 1.061192
2000-01-05 -2.107852 0.199905 0.323586 -0.641630
Item2
A B C D
2000-01-01 -0.587514 0.053897 0.194889 -0.381994
2000-01-02 0.318587 2.089075 -0.728293 -0.090255
2000-01-03 -0.748199 1.318931 -2.029766 0.792652
2000-01-04 0.461007 -0.542749 -0.305384 -0.479195
2000-01-05 0.095031 -0.270099 -0.707140 -0.773882
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 [267]: for row_index, row in df.iterrows():
.....: print('%s\n%s' % (row_index, row))
.....:
0
a 1
b a
Name: 0, dtype: object
1
a 2
b b
Name: 1, dtype: object
2
a 3
b c
Name: 2, dtype: object
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 [268]: df_orig = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])
In [269]: df_orig.dtypes
Out[269]:
int int64
float float64
dtype: object
In [270]: row = next(df_orig.iterrows())[1]
In [271]: row
Out[271]:
int 1.0
float 1.5
Name: 0, dtype: float64
All values in row
, returned as a Series, are now upcasted
to floats, also the original integer value in column x:
In [272]: row['int'].dtype
Out[272]: dtype('float64')
In [273]: df_orig['int'].dtype
Out[273]: 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 [274]: df2 = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
In [275]: print(df2)
x y
0 1 4
1 2 5
2 3 6
In [276]: print(df2.T)
0 1 2
x 1 2 3
y 4 5 6
In [277]: df2_t = pd.DataFrame(dict((idx,values) for idx, values in df2.iterrows()))
In [278]: print(df2_t)
0 1 2
x 1 2 3
y 4 5 6
itertuples¶
The itertuples()
method will return an iterator
yielding a namedtuple for each row in the DataFrame. The first element
of the tuple will be the row’s corresponding index value, while the
remaining values are the row values.
For instance:
In [279]: 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()
.
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.
# datetime
In [280]: s = pd.Series(pd.date_range('20130101 09:10:12', periods=4))
In [281]: s
Out[281]:
0 2013-01-01 09:10:12
1 2013-01-02 09:10:12
2 2013-01-03 09:10:12
3 2013-01-04 09:10:12
dtype: datetime64[ns]
In [282]: s.dt.hour
Out[282]:
0 9
1 9
2 9
3 9
dtype: int64
In [283]: s.dt.second
Out[283]:
0 12
1 12
2 12
3 12
dtype: int64
In [284]: s.dt.day
Out[284]:
0 1
1 2
2 3
3 4
dtype: int64
This enables nice expressions like this:
In [285]: s[s.dt.day==2]
Out[285]:
1 2013-01-02 09:10:12
dtype: datetime64[ns]
You can easily produces tz aware transformations:
In [286]: stz = s.dt.tz_localize('US/Eastern')
In [287]: stz
Out[287]:
0 2013-01-01 09:10:12-05:00
1 2013-01-02 09:10:12-05:00
2 2013-01-03 09:10:12-05:00
3 2013-01-04 09:10:12-05:00
dtype: datetime64[ns, US/Eastern]
In [288]: stz.dt.tz
Out[288]: <DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>
You can also chain these types of operations:
In [289]: s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
Out[289]:
0 2013-01-01 04:10:12-05:00
1 2013-01-02 04:10:12-05:00
2 2013-01-03 04:10:12-05:00
3 2013-01-04 04:10:12-05:00
dtype: datetime64[ns, US/Eastern]
You can also format datetime values as strings with Series.dt.strftime()
which
supports the same format as the standard strftime()
.
# DatetimeIndex
In [290]: s = pd.Series(pd.date_range('20130101', periods=4))
In [291]: s
Out[291]:
0 2013-01-01
1 2013-01-02
2 2013-01-03
3 2013-01-04
dtype: datetime64[ns]
In [292]: s.dt.strftime('%Y/%m/%d')
Out[292]:
0 2013/01/01
1 2013/01/02
2 2013/01/03
3 2013/01/04
dtype: object
# PeriodIndex
In [293]: s = pd.Series(pd.period_range('20130101', periods=4))
In [294]: s
Out[294]:
0 2013-01-01
1 2013-01-02
2 2013-01-03
3 2013-01-04
dtype: object
In [295]: s.dt.strftime('%Y/%m/%d')
Out[295]:
0 2013/01/01
1 2013/01/02
2 2013/01/03
3 2013/01/04
dtype: object
The .dt
accessor works for period and timedelta dtypes.
# period
In [296]: s = pd.Series(pd.period_range('20130101', periods=4, freq='D'))
In [297]: s
Out[297]:
0 2013-01-01
1 2013-01-02
2 2013-01-03
3 2013-01-04
dtype: object
In [298]: s.dt.year
Out[298]:
0 2013
1 2013
2 2013
3 2013
dtype: int64
In [299]: s.dt.day
Out[299]:
0 1
1 2
2 3
3 4
dtype: int64
# timedelta
In [300]: s = pd.Series(pd.timedelta_range('1 day 00:00:05', periods=4, freq='s'))
In [301]: s
Out[301]:
0 1 days 00:00:05
1 1 days 00:00:06
2 1 days 00:00:07
3 1 days 00:00:08
dtype: timedelta64[ns]
In [302]: s.dt.days
Out[302]:
0 1
1 1
2 1
3 1
dtype: int64
In [303]: s.dt.seconds
Out[303]:
0 5
1 6
2 7
3 8
dtype: int64
In [304]: s.dt.components
Out[304]:
days hours minutes seconds milliseconds microseconds nanoseconds
0 1 0 0 5 0 0 0
1 1 0 0 6 0 0 0
2 1 0 0 7 0 0 0
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 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 [305]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat']) In [306]: s.str.lower() Out[306]: 0 a 1 b 2 c 3 aaba 4 baca 5 NaN 6 caba 7 dog 8 cat dtype: object
Powerful pattern-matching methods are provided as well, but note that pattern-matching generally uses regular expressions by default (and in some cases always uses them).
Please see Vectorized String Methods for a complete description.
Sorting¶
Pandas supports three kinds of sorting: sorting by index labels, sorting by column values, and sorting by a combination of both.
By Index¶
The Series.sort_index()
and DataFrame.sort_index()
methods are
used to sort a pandas object by its index levels.
In [307]: 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 [308]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
.....: columns=['three', 'two', 'one'])
.....:
In [309]: unsorted_df
Out[309]:
three two one
a NaN 0.708543 0.036274
d -0.540166 0.586626 NaN
c 0.410238 1.121731 1.044630
b -0.282532 -2.038777 -0.490032
# DataFrame
In [310]: unsorted_df.sort_index()
Out[310]:
three two one
a NaN 0.708543 0.036274
b -0.282532 -2.038777 -0.490032
c 0.410238 1.121731 1.044630
d -0.540166 0.586626 NaN
In [311]: unsorted_df.sort_index(ascending=False)
Out[311]:
three two one
d -0.540166 0.586626 NaN
c 0.410238 1.121731 1.044630
b -0.282532 -2.038777 -0.490032
a NaN 0.708543 0.036274
In [312]: unsorted_df.sort_index(axis=1)
Out[312]:
one three two
a 0.036274 NaN 0.708543
d NaN -0.540166 0.586626
c 1.044630 0.410238 1.121731
b -0.490032 -0.282532 -2.038777
# Series
In [313]: unsorted_df['three'].sort_index()
Out[313]:
a NaN
b -0.282532
c 0.410238
d -0.540166
Name: three, dtype: float64
By Values¶
The Series.sort_values()
method is used to sort a Series by its values. The
DataFrame.sort_values()
method is used to sort a DataFrame by its column or row values.
The optional by
parameter to DataFrame.sort_values()
may used to specify one or more columns
to use to determine the sorted order.
In [314]: df1 = pd.DataFrame({'one':[2,1,1,1],'two':[1,3,2,4],'three':[5,4,3,2]})
In [315]: df1.sort_values(by='two')
Out[315]:
one two three
0 2 1 5
2 1 2 3
1 1 3 4
3 1 4 2
The by
parameter can take a list of column names, e.g.:
In [316]: df1[['one', 'two', 'three']].sort_values(by=['one','two'])
Out[316]:
one two three
2 1 2 3
1 1 3 4
3 1 4 2
0 2 1 5
These methods have special treatment of NA values via the na_position
argument:
In [317]: s[2] = np.nan
In [318]: s.sort_values()
Out[318]:
0 A
3 Aaba
1 B
4 Baca
6 CABA
8 cat
7 dog
2 NaN
5 NaN
dtype: object
In [319]: s.sort_values(na_position='first')
Out[319]:
2 NaN
5 NaN
0 A
3 Aaba
1 B
4 Baca
6 CABA
8 cat
7 dog
dtype: object
By Indexes and Values¶
New in version 0.23.0.
Strings passed as the by
parameter to DataFrame.sort_values()
may
refer to either columns or index level names.
# Build MultiIndex
In [320]: idx = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('a', 2),
.....: ('b', 2), ('b', 1), ('b', 1)])
.....:
In [321]: idx.names = ['first', 'second']
# Build DataFrame
In [322]: df_multi = pd.DataFrame({'A': np.arange(6, 0, -1)},
.....: index=idx)
.....:
In [323]: df_multi
Out[323]:
A
first second
a 1 6
2 5
2 4
b 2 3
1 2
1 1
Sort by ‘second’ (index) and ‘A’ (column)
In [324]: df_multi.sort_values(by=['second', 'A'])
Out[324]:
A
first second
b 1 1
1 2
a 1 6
b 2 3
a 2 4
2 5
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 [325]: ser = pd.Series([1, 2, 3])
In [326]: ser.searchsorted([0, 3])
Out[326]: array([0, 2])
In [327]: ser.searchsorted([0, 4])
Out[327]: array([0, 3])
In [328]: ser.searchsorted([1, 3], side='right')
Out[328]: array([1, 3])
In [329]: ser.searchsorted([1, 3], side='left')
Out[329]: array([0, 2])
In [330]: ser = pd.Series([3, 1, 2])
In [331]: ser.searchsorted([0, 3], sorter=np.argsort(ser))
Out[331]: array([0, 2])
smallest / largest values¶
Series
has the nsmallest()
and nlargest()
methods which return the
smallest or largest n values. For a large Series
this can be much
faster than sorting the entire Series and calling head(n)
on the result.
In [332]: s = pd.Series(np.random.permutation(10))
In [333]: s
Out[333]:
0 8
1 2
2 9
3 5
4 6
5 0
6 1
7 7
8 4
9 3
dtype: int64
In [334]: s.sort_values()
Out[334]:
5 0
6 1
1 2
9 3
8 4
3 5
4 6
7 7
0 8
2 9
dtype: int64
In [335]: s.nsmallest(3)
Out[335]:
5 0
6 1
1 2
dtype: int64
In [336]: s.nlargest(3)
Out[336]:
2 9
0 8
7 7
dtype: int64
DataFrame
also has the nlargest
and nsmallest
methods.
In [337]: 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 [338]: df.nlargest(3, 'a')
Out[338]:
a b c
5 11 f 3.0
3 10 c 3.2
4 8 e NaN
In [339]: df.nlargest(5, ['a', 'c'])
Out[339]:
a b c
6 -1 f 4.0
5 11 f 3.0
3 10 c 3.2
4 8 e NaN
2 1 d 4.0
In [340]: df.nsmallest(3, 'a')
Out[340]:
a b c
0 -2 a 1.0
1 -1 b 2.0
6 -1 f 4.0
In [341]: df.nsmallest(5, ['a', 'c'])
Out[341]:
a b c
0 -2 a 1.0
2 1 d 4.0
4 8 e NaN
1 -1 b 2.0
6 -1 f 4.0
Sorting by a multi-index column¶
You must be explicit about sorting when the column is a multi-index, and fully specify
all levels to by
.
In [342]: df1.columns = pd.MultiIndex.from_tuples([('a','one'),('a','two'),('b','three')])
In [343]: df1.sort_values(by=('a','two'))
Out[343]:
a b
one two three
0 2 1 5
2 1 2 3
1 1 3 4
3 1 4 2
Copying¶
The copy()
method on pandas objects copies the underlying data (though not
the axis indexes, since they are immutable) and returns a new object. Note that
it is seldom necessary to copy objects. For example, there are only a
handful of ways to alter a DataFrame in-place:
- Inserting, deleting, or modifying a column.
- Assigning to the
index
orcolumns
attributes.- For homogeneous data, directly modifying the values via the
values
attribute or advanced indexing.
To be clear, no pandas method has the side effect of modifying your data; almost every method returns a new object, leaving the original object untouched. If the data is modified, it is because you did so explicitly.
dtypes¶
The main types stored in pandas objects are float
, int
, bool
,
datetime64[ns]
and datetime64[ns, tz]
, timedelta[ns]
,
category
and object
. In addition these dtypes have item sizes, e.g.
int64
and int32
. See Series with TZ
for more detail on datetime64[ns, tz]
dtypes.
A convenient dtypes
attribute for DataFrame returns a Series
with the data type of each column.
In [344]: dft = pd.DataFrame(dict(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 [345]: dft
Out[345]:
A B C D E F G
0 0.809585 1 foo 2001-01-02 1.0 False 1
1 0.128238 1 foo 2001-01-02 1.0 False 1
2 0.775752 1 foo 2001-01-02 1.0 False 1
In [346]: dft.dtypes
Out[346]:
A float64
B int64
C object
D datetime64[ns]
E float32
F bool
G int8
dtype: object
On a Series
object, use the dtype
attribute.
In [347]: dft['A'].dtype
Out[347]: 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 floats
In [348]: pd.Series([1, 2, 3, 4, 5, 6.])
Out[348]:
0 1.0
1 2.0
2 3.0
3 4.0
4 5.0
5 6.0
dtype: float64
# string data forces an ``object`` dtype
In [349]: pd.Series([1, 2, 3, 6., 'foo'])
Out[349]:
0 1
1 2
2 3
3 6
4 foo
dtype: object
The number of columns of each type in a DataFrame
can be found by calling
get_dtype_counts()
.
In [350]: dft.get_dtype_counts()
Out[350]:
float64 1
float32 1
int64 1
int8 1
datetime64[ns] 1
bool 1
object 1
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.
In [351]: df1 = pd.DataFrame(np.random.randn(8, 1), columns=['A'], dtype='float32')
In [352]: df1
Out[352]:
A
0 0.890400
1 0.283331
2 -0.303613
3 -1.192210
4 0.065420
5 0.455918
6 2.008328
7 0.188942
In [353]: df1.dtypes
Out[353]:
A float32
dtype: object
In [354]: df2 = pd.DataFrame(dict( 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 [355]: df2
Out[355]:
A B C
0 -0.454346 0.200071 255
1 -0.916504 -0.557756 255
2 0.640625 -0.141988 0
3 2.675781 -0.174060 0
4 -0.007866 0.258626 0
5 -0.204224 0.941688 0
6 -0.100098 -1.849045 0
7 -0.402100 -0.949458 0
In [356]: df2.dtypes
Out[356]:
A float16
B float64
C uint8
dtype: object
defaults¶
By default integer types are int64
and float types are float64
,
regardless of platform (32-bit or 64-bit).
The following will all result in int64
dtypes.
In [357]: pd.DataFrame([1, 2], columns=['a']).dtypes
Out[357]:
a int64
dtype: object
In [358]: pd.DataFrame({'a': [1, 2]}).dtypes
Out[358]:
a int64
dtype: object
In [359]: pd.DataFrame({'a': 1 }, index=list(range(2))).dtypes
Out[359]:
a int64
dtype: object
Note that Numpy will choose platform-dependent types when creating arrays.
The following WILL result in int32
on 32-bit platform.
In [360]: 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 [361]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2
In [362]: df3
Out[362]:
A B C
0 0.436054 0.200071 255.0
1 -0.633173 -0.557756 255.0
2 0.337012 -0.141988 0.0
3 1.483571 -0.174060 0.0
4 0.057555 0.258626 0.0
5 0.251695 0.941688 0.0
6 1.908231 -1.849045 0.0
7 -0.213158 -0.949458 0.0
In [363]: df3.dtypes
Out[363]:
A float32
B float64
C float64
dtype: object
The values
attribute on a DataFrame return the lower-common-denominator of the dtypes, meaning
the dtype that can accommodate ALL of the types in the resulting homogeneous dtyped NumPy array. This can
force some upcasting.
In [364]: df3.values.dtype
Out[364]: 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 [365]: df3
Out[365]:
A B C
0 0.436054 0.200071 255.0
1 -0.633173 -0.557756 255.0
2 0.337012 -0.141988 0.0
3 1.483571 -0.174060 0.0
4 0.057555 0.258626 0.0
5 0.251695 0.941688 0.0
6 1.908231 -1.849045 0.0
7 -0.213158 -0.949458 0.0
In [366]: df3.dtypes
Out[366]:
A float32
B float64
C float64
dtype: object
# conversion of dtypes
In [367]: df3.astype('float32').dtypes
Out[367]:
A float32
B float32
C float32
dtype: object
Convert a subset of columns to a specified type using astype()
.
In [368]: dft = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
In [369]: dft[['a','b']] = dft[['a','b']].astype(np.uint8)
In [370]: dft
Out[370]:
a b c
0 1 4 7
1 2 5 8
2 3 6 9
In [371]: dft.dtypes
Out[371]:
a uint8
b uint8
c int64
dtype: object
New in version 0.19.0.
Convert certain columns to a specific dtype by passing a dict to astype()
.
In [372]: dft1 = pd.DataFrame({'a': [1,0,1], 'b': [4,5,6], 'c': [7, 8, 9]})
In [373]: dft1 = dft1.astype({'a': np.bool, 'c': np.float64})
In [374]: dft1
Out[374]:
a b c
0 True 4 7.0
1 False 5 8.0
2 True 6 9.0
In [375]: dft1.dtypes
Out[375]:
a bool
b int64
c float64
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.
In [376]: dft = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
In [377]: dft.loc[:, ['a', 'b']].astype(np.uint8).dtypes
Out[377]:
a uint8
b uint8
dtype: object
In [378]: dft.loc[:, ['a', 'b']] = dft.loc[:, ['a', 'b']].astype(np.uint8)
In [379]: dft.dtypes
Out[379]:
a int64
b int64
c int64
dtype: object
object conversion¶
pandas offers various functions to try to force conversion of types from the object
dtype to other types.
In cases where the data is already of the correct type, but stored in an object
array, the
DataFrame.infer_objects()
and Series.infer_objects()
methods can be used to soft convert
to the correct type.
In [380]: import datetime In [381]: df = pd.DataFrame([[1, 2], .....: ['a', 'b'], .....: [datetime.datetime(2016, 3, 2), datetime.datetime(2016, 3, 2)]]) .....: In [382]: df = df.T In [383]: df Out[383]: 0 1 2 0 1 a 2016-03-02 00:00:00 1 2 b 2016-03-02 00:00:00 In [384]: df.dtypes Out[384]: 0 object 1 object 2 object dtype: object
Because the data was transposed the original inference stored all columns as object, which
infer_objects
will correct.
In [385]: df.infer_objects().dtypes Out[385]: 0 int64 1 object 2 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 [386]: m = ['1.1', 2, 3] In [387]: pd.to_numeric(m) Out[387]: array([ 1.1, 2. , 3. ])
to_datetime()
(conversion to datetime objects)In [388]: import datetime In [389]: m = ['2016-07-09', datetime.datetime(2016, 3, 2)] In [390]: pd.to_datetime(m) Out[390]: DatetimeIndex(['2016-07-09', '2016-03-02'], dtype='datetime64[ns]', freq=None)
to_timedelta()
(conversion to timedelta objects)In [391]: m = ['5us', pd.Timedelta('1day')] In [392]: pd.to_timedelta(m) Out[392]: 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 [393]: import datetime
In [394]: m = ['apple', datetime.datetime(2016, 3, 2)]
In [395]: pd.to_datetime(m, errors='coerce')
Out[395]: DatetimeIndex(['NaT', '2016-03-02'], dtype='datetime64[ns]', freq=None)
In [396]: m = ['apple', 2, 3]
In [397]: pd.to_numeric(m, errors='coerce')
Out[397]: array([ nan, 2., 3.])
In [398]: m = ['apple', pd.Timedelta('1day')]
In [399]: pd.to_timedelta(m, errors='coerce')
Out[399]: 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 [400]: import datetime
In [401]: m = ['apple', datetime.datetime(2016, 3, 2)]
In [402]: pd.to_datetime(m, errors='ignore')
Out[402]: array(['apple', datetime.datetime(2016, 3, 2, 0, 0)], dtype=object)
In [403]: m = ['apple', 2, 3]
In [404]: pd.to_numeric(m, errors='ignore')
Out[404]: array(['apple', 2, 3], dtype=object)
In [405]: m = ['apple', pd.Timedelta('1day')]
In [406]: pd.to_timedelta(m, errors='ignore')
Out[406]: 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 [407]: m = ['1', 2, 3]
In [408]: pd.to_numeric(m, downcast='integer') # smallest signed int dtype
Out[408]: array([1, 2, 3], dtype=int8)
In [409]: pd.to_numeric(m, downcast='signed') # same as 'integer'
Out[409]: array([1, 2, 3], dtype=int8)
In [410]: pd.to_numeric(m, downcast='unsigned') # smallest unsigned int dtype
Out[410]: array([1, 2, 3], dtype=uint8)
In [411]: pd.to_numeric(m, downcast='float') # smallest float dtype
Out[411]: 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 [412]: import datetime
In [413]: df = pd.DataFrame([['2016-07-09', datetime.datetime(2016, 3, 2)]] * 2, dtype='O')
In [414]: df
Out[414]:
0 1
0 2016-07-09 2016-03-02 00:00:00
1 2016-07-09 2016-03-02 00:00:00
In [415]: df.apply(pd.to_datetime)
Out[415]:
0 1
0 2016-07-09 2016-03-02
1 2016-07-09 2016-03-02
In [416]: df = pd.DataFrame([['1.1', 2, 3]] * 2, dtype='O')
In [417]: df
Out[417]:
0 1 2
0 1.1 2 3
1 1.1 2 3
In [418]: df.apply(pd.to_numeric)
Out[418]:
0 1 2
0 1.1 2 3
1 1.1 2 3
In [419]: df = pd.DataFrame([['5us', pd.Timedelta('1day')]] * 2, dtype='O')
In [420]: df
Out[420]:
0 1
0 5us 1 days 00:00:00
1 5us 1 days 00:00:00
In [421]: df.apply(pd.to_timedelta)
Out[421]:
0 1
0 00:00:00.000005 1 days
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.
In [422]: dfi = df3.astype('int32')
In [423]: dfi['E'] = 1
In [424]: dfi
Out[424]:
A B C E
0 0 0 255 1
1 0 0 255 1
2 0 0 0 1
3 1 0 0 1
4 0 0 0 1
5 0 0 0 1
6 1 -1 0 1
7 0 0 0 1
In [425]: dfi.dtypes
Out[425]:
A int32
B int32
C int32
E int64
dtype: object
In [426]: casted = dfi[dfi>0]
In [427]: casted
Out[427]:
A B C E
0 NaN NaN 255.0 1
1 NaN NaN 255.0 1
2 NaN NaN NaN 1
3 1.0 NaN NaN 1
4 NaN NaN NaN 1
5 NaN NaN NaN 1
6 1.0 NaN NaN 1
7 NaN NaN NaN 1
In [428]: casted.dtypes
Out[428]:
A float64
B float64
C float64
E int64
dtype: object
While float dtypes are unchanged.
In [429]: dfa = df3.copy()
In [430]: dfa['A'] = dfa['A'].astype('float32')
In [431]: dfa.dtypes
Out[431]:
A float32
B float64
C float64
dtype: object
In [432]: casted = dfa[df2>0]
In [433]: casted
Out[433]:
A B C
0 NaN 0.200071 255.0
1 NaN NaN 255.0
2 0.337012 NaN NaN
3 1.483571 NaN NaN
4 NaN 0.258626 NaN
5 NaN 0.941688 NaN
6 NaN NaN NaN
7 NaN NaN NaN
In [434]: casted.dtypes
Out[434]:
A float32
B float64
C float64
dtype: object
Selecting columns based on dtype
¶
The select_dtypes()
method implements subsetting of columns
based on their dtype
.
First, let’s create a DataFrame
with a slew of different
dtypes:
In [435]: 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).values,
.....: 'category': pd.Series(list("ABC")).astype('category')})
.....:
In [436]: df['tdeltas'] = df.dates.diff()
In [437]: df['uint64'] = np.arange(3, 6).astype('u8')
In [438]: df['other_dates'] = pd.date_range('20130101', periods=3).values
In [439]: df['tz_aware_dates'] = pd.date_range('20130101', periods=3, tz='US/Eastern')
In [440]: df
Out[440]:
string int64 uint8 float64 bool1 ... category tdeltas uint64 other_dates tz_aware_dates
0 a 1 3 4.0 True ... A NaT 3 2013-01-01 2013-01-01 00:00:00-05:00
1 b 2 4 5.0 False ... B 1 days 4 2013-01-02 2013-01-02 00:00:00-05:00
2 c 3 5 6.0 True ... C 1 days 5 2013-01-03 2013-01-03 00:00:00-05:00
[3 rows x 12 columns]
And the dtypes:
In [441]: df.dtypes
Out[441]:
string object
int64 int64
uint8 uint8
float64 float64
bool1 bool
bool2 bool
dates datetime64[ns]
category category
tdeltas timedelta64[ns]
uint64 uint64
other_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 [442]: df.select_dtypes(include=[bool])
Out[442]:
bool1 bool2
0 True False
1 False True
2 True False
You can also pass the name of a dtype in the NumPy dtype hierarchy:
In [443]: df.select_dtypes(include=['bool'])
Out[443]:
bool1 bool2
0 True False
1 False True
2 True False
select_dtypes()
also works with generic dtypes as well.
For example, to select all numeric and boolean columns while excluding unsigned integers:
In [444]: df.select_dtypes(include=['number', 'bool'], exclude=['unsignedinteger'])
Out[444]:
int64 float64 bool1 bool2 tdeltas
0 1 4.0 True False NaT
1 2 5.0 False True 1 days
2 3 6.0 True False 1 days
To select string columns you must use the object
dtype:
In [445]: df.select_dtypes(include=['object'])
Out[445]:
string
0 a
1 b
2 c
To see all the child dtypes of a generic dtype
like numpy.number
you
can define a function that returns a tree of child dtypes:
In [446]: 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 [447]: subdtypes(np.generic)
Out[447]:
[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_]]
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.