Essential basic functionality¶
Here we discuss a lot of the essential functionality common to the pandas data structures. Here’s how to create some of the objects used in the examples from the previous section:
In [1]: index = date_range('1/1/2000', periods=8)
In [2]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [3]: df = DataFrame(randn(8, 3), index=index,
...: columns=['A', 'B', 'C'])
...:
In [4]: wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'],
...: major_axis=date_range('1/1/2000', periods=5),
...: minor_axis=['A', 'B', 'C', 'D'])
...:
Head and Tail¶
To view a small sample of a Series or DataFrame object, use the head and tail methods. The default number of elements to display is five, but you may pass a custom number.
In [5]: long_series = Series(randn(1000))
In [6]: long_series.head()
Out[6]:
0 0.335504
1 0.269719
2 -0.098057
3 -0.526786
4 0.896511
In [7]: long_series.tail(3)
Out[7]:
997 1.361478
998 0.319943
999 -0.934244
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.983003 -0.796896 -1.688996
2000-01-02 1.060319 1.618764 0.701717
In [9]: df.columns = [x.lower() for x in df.columns]
In [10]: df
Out[10]:
a b c
2000-01-01 -0.983003 -0.796896 -1.688996
2000-01-02 1.060319 1.618764 0.701717
2000-01-03 -0.221476 -0.143426 1.157109
2000-01-04 1.573618 0.789571 1.184530
2000-01-05 -1.313863 -0.208595 0.240951
2000-01-06 -0.180712 -0.229452 1.034335
2000-01-07 -0.040443 -0.472683 1.159358
2000-01-08 1.206865 0.690638 -0.168824
To get the actual data inside a data structure, one need only access the values property:
In [11]: s.values
Out[11]: array([ 2.0066, 0.5081, 0.1165, -0.6522, -0.2912])
In [12]: df.values
Out[12]:
array([[-0.983 , -0.7969, -1.689 ],
[ 1.0603, 1.6188, 0.7017],
[-0.2215, -0.1434, 1.1571],
[ 1.5736, 0.7896, 1.1845],
[-1.3139, -0.2086, 0.241 ],
[-0.1807, -0.2295, 1.0343],
[-0.0404, -0.4727, 1.1594],
[ 1.2069, 0.6906, -0.1688]])
In [13]: wp.values
Out[13]:
array([[[ 0.6371, 0.236 , 0.5881, 0.4055],
[ 0.5632, 0.2592, -0.0239, 0.6453],
[-0.4783, 0.1582, -0.628 , -0.718 ],
[ 1.8318, 0.3024, -0.1126, 1.1123],
[-0.6902, 0.2105, -1.2264, 0.4147]],
[[-1.6552, -0.3444, 1.1404, -0.2254],
[-0.2462, -0.6313, 1.018 , -1.0681],
[-0.1739, -0.8775, -1.0366, -0.9515],
[ 0.8671, 1.5971, -0.1907, 0.1615],
[ 0.3245, -0.185 , -1.0757, 0.8194]]])
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.
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
Out[14]:
one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218
In [15]: row = df.ix[1]
In [16]: column = df['two']
In [17]: df.sub(row, axis='columns')
Out[17]:
one three two
a -0.457558 NaN -1.165533
b 0.000000 0.000000 0.000000
c 3.172225 -0.791578 -0.552879
d NaN 0.284071 -1.525895
In [18]: df.sub(row, axis=1)
Out[18]:
one three two
a -0.457558 NaN -1.165533
b 0.000000 0.000000 0.000000
c 3.172225 -0.791578 -0.552879
d NaN 0.284071 -1.525895
In [19]: df.sub(column, axis='index')
Out[19]:
one three two
a -0.690661 NaN 0
b -1.398636 -0.284609 0
c 2.326468 -0.523309 0
d NaN 1.525356 0
In [20]: df.sub(column, axis=0)
Out[20]:
one three two
a -0.690661 NaN 0
b -1.398636 -0.284609 0
c 2.326468 -0.523309 0
d NaN 1.525356 0
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 [21]: major_mean = wp.mean(axis='major')
In [22]: major_mean
Out[22]:
Item1 Item2
A 0.372700 -0.176754
B 0.233256 -0.088221
C -0.280561 -0.028928
D 0.371969 -0.252780
In [23]: wp.sub(major_mean, axis='major')
Out[23]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 5 (major) x 4 (minor)
Items: Item1 to Item2
Major axis: 2000-01-01 00:00:00 to 2000-01-05 00:00:00
Minor axis: A to D
And similarly for axis="items" and axis="minor".
Note
I could be convinced to make the axis argument in the DataFrame methods match the broadcasting behavior of Panel. Though it would require a transition period so users can change their code...
Missing data / operations with fill values¶
In Series and DataFrame (though not yet in Panel), the arithmetic functions have the option of inputting a fill_value, namely a value to substitute when at most one of the values at a location are missing. For example, when adding two DataFrame objects, you may wish to treat NaN as 0 unless both DataFrames are missing that value, in which case the result will be NaN (you can later replace NaN with some other value using fillna if you wish).
In [24]: df
Out[24]:
one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218
In [25]: df2
Out[25]:
one three two
a -0.870517 1.000000 -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218
In [26]: df + df2
Out[26]:
one three two
a -1.741035 NaN -0.359713
b -0.825919 1.402134 1.971353
c 5.518530 -0.181022 0.865595
d NaN 1.970276 -1.080436
In [27]: df.add(df2, fill_value=0)
Out[27]:
one three two
a -1.741035 1.000000 -0.359713
b -0.825919 1.402134 1.971353
c 5.518530 -0.181022 0.865595
d NaN 1.970276 -1.080436
Flexible Comparisons¶
Starting in v0.8, pandas introduced binary comparison methods eq, ne, lt, gt, le, and ge to Series and DataFrame whose behavior is analogous to the binary arithmetic operations described above:
In [28]: df.gt(df2)
Out[28]:
one three two
a False False False
b False False False
c False False False
d False False False
In [29]: df2.ne(df)
Out[29]:
one three two
a False True False
b False False False
c False False False
d True False 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 [30]: df1 = DataFrame({'A' : [1., np.nan, 3., 5., np.nan],
....: 'B' : [np.nan, 2., 3., np.nan, 6.]})
....:
In [31]: df2 = DataFrame({'A' : [5., 2., 4., np.nan, 3., 7.],
....: 'B' : [np.nan, np.nan, 3., 4., 6., 8.]})
....:
In [32]: df1
Out[32]:
A B
0 1 NaN
1 NaN 2
2 3 3
3 5 NaN
4 NaN 6
In [33]: df2
Out[33]:
A B
0 5 NaN
1 2 NaN
2 4 3
3 NaN 4
4 3 6
5 7 8
In [34]: df1.combine_first(df2)
Out[34]:
A B
0 1 NaN
1 2 2
2 3 3
3 5 4
4 3 6
5 7 8
General DataFrame Combine¶
The combine_first method above calls the more general DataFrame method combine. This method takes another DataFrame and a combiner function, aligns the input DataFrame and then passes the combiner function pairs of Series (ie, columns whose names are the same).
So, for instance, to reproduce combine_first as above:
In [35]: combiner = lambda x, y: np.where(isnull(x), y, x)
In [36]: df1.combine(df2, combiner)
Out[36]:
A B
0 1 NaN
1 2 2
2 3 3
3 5 4
4 3 6
5 7 8
Descriptive statistics¶
A large number of methods for computing descriptive statistics and other related operations on Series, DataFrame, and Panel. Most of these are aggregations (hence producing a lower-dimensional result) like sum, mean, and quantile, but some of them, like cumsum and cumprod, produce an object of the same size. Generally speaking, these methods take an axis argument, just like ndarray.{sum, std, ...}, but the axis can be specified by name or integer:
- Series: no axis argument needed
- DataFrame: “index” (axis=0, default), “columns” (axis=1)
- Panel: “items” (axis=0), “major” (axis=1, default), “minor” (axis=2)
For example:
In [37]: df
Out[37]:
one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218
In [38]: df.mean(0)
Out[38]:
one 0.491929
three 0.531898
two 0.174600
In [39]: df.mean(1)
Out[39]:
a -0.525187
b 0.424595
c 1.033851
d 0.222460
All such methods have a skipna option signaling whether to exclude missing data (True by default):
In [40]: df.sum(0, skipna=False)
Out[40]:
one NaN
three NaN
two 0.6984
In [41]: df.sum(axis=1, skipna=True)
Out[41]:
a -1.050374
b 1.273784
c 3.101552
d 0.444920
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 [42]: ts_stand = (df - df.mean()) / df.std()
In [43]: ts_stand.std()
Out[43]:
one 1
three 1
two 1
In [44]: xs_stand = df.sub(df.mean(1), axis=0).div(df.std(1), axis=0)
In [45]: xs_stand.std(1)
Out[45]:
a 1
b 1
c 1
d 1
Note that methods like cumsum and cumprod preserve the location of NA values:
In [46]: df.cumsum()
Out[46]:
one three two
a -0.870517 NaN -0.179856
b -1.283477 0.701067 0.805820
c 1.475788 0.610556 1.238618
d NaN 1.595694 0.698400
Here is a quick reference summary table of common functions. Each also takes an optional level parameter which applies only if the object has a hierarchical index.
Function | Description |
---|---|
count | Number of non-null observations |
sum | Sum of values |
mean | Mean of values |
mad | Mean absolute deviation |
median | Arithmetic median of values |
min | Minimum |
max | Maximum |
abs | Absolute Value |
prod | Product of values |
std | Unbiased standard deviation |
var | Unbiased variance |
skew | Unbiased skewness (3rd moment) |
kurt | Unbiased kurtosis (4th moment) |
quantile | Sample quantile (value at %) |
cumsum | Cumulative sum |
cumprod | Cumulative product |
cummax | Cumulative maximum |
cummin | Cumulative minimum |
Note that by chance some NumPy methods, like mean, std, and sum, will exclude NAs on Series input by default:
In [47]: np.mean(df['one'])
Out[47]: 0.4919294526810159
In [48]: np.mean(df['one'].values)
Out[48]: nan
Series also has a method nunique which will return the number of unique non-null values:
In [49]: series = Series(randn(500))
In [50]: series[20:500] = np.nan
In [51]: series[10:20] = 5
In [52]: series.nunique()
Out[52]: 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 [53]: series = Series(randn(1000))
In [54]: series[::2] = np.nan
In [55]: series.describe()
Out[55]:
count 500.000000
mean -0.020938
std 1.010248
min -3.281617
25% -0.687009
50% -0.056300
75% 0.657131
max 2.735593
In [56]: frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])
In [57]: frame.ix[::2] = np.nan
In [58]: frame.describe()
Out[58]:
a b c d e
count 500.000000 500.000000 500.000000 500.000000 500.000000
mean -0.048015 0.054843 0.062752 -0.063190 -0.014026
std 1.022844 1.028833 0.976080 0.970559 0.992620
min -3.033710 -3.189738 -2.950164 -2.848784 -2.558847
25% -0.704183 -0.625279 -0.542446 -0.719371 -0.763581
50% -0.048535 0.064119 0.016228 -0.039262 0.018997
75% 0.613895 0.711665 0.699206 0.504007 0.629266
max 2.800058 3.211389 3.111206 3.266256 2.493795
For a non-numerical Series object, describe will give a simple summary of the number of unique values and most frequently occurring values:
In [59]: s = Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])
In [60]: s.describe()
Out[60]:
count 9
unique 4
top a
freq 5
There also is a utility function, value_range which takes a DataFrame and returns a series with the minimum/maximum values in the DataFrame.
Index of Min/Max Values¶
The idxmin and idxmax functions on Series and DataFrame compute the index labels with the minimum and maximum corresponding values:
In [61]: s1 = Series(randn(5))
In [62]: s1
Out[62]:
0 0.223436
1 0.242724
2 -0.424091
3 -1.408992
4 -0.835075
In [63]: s1.idxmin(), s1.idxmax()
Out[63]: (3, 1)
In [64]: df1 = DataFrame(randn(5,3), columns=['A','B','C'])
In [65]: df1
Out[65]:
A B C
0 -0.715335 -1.004579 0.415654
1 -1.534674 -0.378600 0.663463
2 0.730815 -0.886041 -0.243434
3 -0.288722 -1.069535 0.513199
4 -2.273450 0.576698 -0.972615
In [66]: df1.idxmin(axis=0)
Out[66]:
A 4
B 3
C 4
In [67]: df1.idxmax(axis=1)
Out[67]:
0 C
1 C
2 A
3 C
4 B
When there are multiple rows (or columns) matching the minimum or maximum value, idxmin and idxmax return the first matching index:
In [68]: df3 = DataFrame([2, 1, 1, 3, np.nan], columns=['A'], index=list('edcba'))
In [69]: df3
Out[69]:
A
e 2
d 1
c 1
b 3
a NaN
In [70]: df3['A'].idxmin()
Out[70]: 'd'
Value counts (histogramming)¶
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 [71]: data = np.random.randint(0, 7, size=50)
In [72]: data
Out[72]:
array([3, 5, 0, 5, 0, 4, 4, 1, 6, 5, 1, 6, 4, 6, 3, 5, 3, 3, 0, 4, 6, 2, 2,
3, 5, 6, 3, 6, 3, 5, 3, 4, 2, 3, 2, 1, 3, 0, 4, 3, 6, 3, 5, 0, 2, 3,
4, 0, 6, 6])
In [73]: s = Series(data)
In [74]: s.value_counts()
Out[74]:
3 13
6 9
5 7
4 7
0 6
2 5
1 3
In [75]: value_counts(data)
Out[75]:
3 13
6 9
5 7
4 7
0 6
2 5
1 3
Discretization and quantiling¶
Continuous values can be discretized using the cut (bins based on values) and qcut (bins based on sample quantiles) functions:
In [76]: arr = np.random.randn(20)
In [77]: factor = cut(arr, 4)
In [78]: factor
Out[78]:
Categorical:
array([(-1.522, -0.591], (0.34, 1.272], (-0.591, 0.34], (-0.591, 0.34],
(-0.591, 0.34], (-1.522, -0.591], (0.34, 1.272], (0.34, 1.272],
(-0.591, 0.34], (0.34, 1.272], (0.34, 1.272], (0.34, 1.272],
(0.34, 1.272], (-0.591, 0.34], (-0.591, 0.34], (0.34, 1.272],
(-1.522, -0.591], (-2.457, -1.522], (-2.457, -1.522],
(-2.457, -1.522]], dtype=object)
Levels (4): Index([(-2.457, -1.522], (-1.522, -0.591], (-0.591, 0.34],
(0.34, 1.272]], dtype=object)
In [79]: factor = cut(arr, [-5, -1, 0, 1, 5])
In [80]: factor
Out[80]:
Categorical:
array([(-1, 0], (1, 5], (-1, 0], (-1, 0], (-1, 0], (-5, -1], (0, 1],
(0, 1], (-1, 0], (0, 1], (0, 1], (0, 1], (1, 5], (-1, 0], (-1, 0],
(0, 1], (-5, -1], (-5, -1], (-5, -1], (-5, -1]], dtype=object)
Levels (4): Index([(-5, -1], (-1, 0], (0, 1], (1, 5]], dtype=object)
qcut computes sample quantiles. For example, we could slice up some normally distributed data into equal-size quartiles like so:
In [81]: arr = np.random.randn(30)
In [82]: factor = qcut(arr, [0, .25, .5, .75, 1])
In [83]: factor
Out[83]:
Categorical:
array([(0.154, 0.519], (-0.564, 0.154], [-1.306, -0.564], (0.154, 0.519],
(-0.564, 0.154], [-1.306, -0.564], (0.519, 2.147], [-1.306, -0.564],
(0.519, 2.147], (0.154, 0.519], [-1.306, -0.564], [-1.306, -0.564],
(0.519, 2.147], (0.154, 0.519], (-0.564, 0.154], [-1.306, -0.564],
(0.154, 0.519], (0.154, 0.519], (-0.564, 0.154], [-1.306, -0.564],
(0.519, 2.147], (0.519, 2.147], (0.519, 2.147], (0.519, 2.147],
[-1.306, -0.564], (0.154, 0.519], (0.519, 2.147], (-0.564, 0.154],
(-0.564, 0.154], (-0.564, 0.154]], dtype=object)
Levels (4): Index([[-1.306, -0.564], (-0.564, 0.154], (0.154, 0.519],
(0.519, 2.147]], dtype=object)
In [84]: value_counts(factor)
Out[84]:
[-1.306, -0.564] 8
(0.519, 2.147] 8
(0.154, 0.519] 7
(-0.564, 0.154] 7
Function application¶
Arbitrary functions can be applied along the axes of a DataFrame or Panel using the apply method, which, like the descriptive statistics methods, take an optional axis argument:
In [85]: df.apply(np.mean)
Out[85]:
one 0.491929
three 0.531898
two 0.174600
In [86]: df.apply(np.mean, axis=1)
Out[86]:
a -0.525187
b 0.424595
c 1.033851
d 0.222460
In [87]: df.apply(lambda x: x.max() - x.min())
Out[87]:
one 3.629783
three 1.075649
two 1.525895
In [88]: df.apply(np.cumsum)
Out[88]:
one three two
a -0.870517 NaN -0.179856
b -1.283477 0.701067 0.805820
c 1.475788 0.610556 1.238618
d NaN 1.595694 0.698400
In [89]: df.apply(np.exp)
Out[89]:
one three two
a 0.418735 NaN 0.835390
b 0.661689 2.015903 2.679624
c 15.788238 0.913464 1.541564
d NaN 2.678181 0.582621
Depending on the return type of the function passed to apply, the result will either be of lower dimension or the same dimension.
apply combined with some cleverness can be used to answer many questions about a data set. For example, suppose we wanted to extract the date where the maximum value for each column occurred:
In [90]: tsdf = DataFrame(randn(1000, 3), columns=['A', 'B', 'C'],
....: index=date_range('1/1/2000', periods=1000))
....:
In [91]: tsdf.apply(lambda x: x.index[x.dropna().argmax()])
Out[91]:
A 2002-08-06 00:00:00
B 2001-02-05 00:00:00
C 2001-10-17 00:00:00
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 [92]: tsdf
Out[92]:
A B C
2000-01-01 0.397163 -0.274735 1.330425
2000-01-02 0.962257 -1.558382 0.297888
2000-01-03 -0.532658 0.223648 -0.450402
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.496078 -0.134822 -2.056432
2000-01-09 -0.458635 -1.083705 1.901762
2000-01-10 -0.471860 2.021949 0.344832
In [93]: tsdf.apply(Series.interpolate)
Out[93]:
A B C
2000-01-01 0.397163 -0.274735 1.330425
2000-01-02 0.962257 -1.558382 0.297888
2000-01-03 -0.532658 0.223648 -0.450402
2000-01-04 -0.725342 0.151954 -0.771608
2000-01-05 -0.918026 0.080260 -1.092814
2000-01-06 -1.110710 0.008566 -1.414020
2000-01-07 -1.303394 -0.063128 -1.735226
2000-01-08 -1.496078 -0.134822 -2.056432
2000-01-09 -0.458635 -1.083705 1.901762
2000-01-10 -0.471860 2.021949 0.344832
Finally, apply takes an argument raw which is False by default, which converts each row or column into a Series before applying the function. When set to True, the passed function will instead receive an ndarray object, which has positive performance implications if you do not need the indexing functionality.
See also
The section on GroupBy demonstrates related, flexible functionality for grouping by some criterion, applying, and combining the results into a Series, DataFrame, etc.
Applying elementwise Python functions¶
Since not all functions can be vectorized (accept NumPy arrays and return another array or value), the methods applymap on DataFrame and analogously map on Series accept any Python function taking a single value and returning a single value. For example:
In [94]: f = lambda x: len(str(x))
In [95]: df['one'].map(f)
Out[95]:
a 15
b 15
c 13
d 3
Name: one
In [96]: df.applymap(f)
Out[96]:
one three two
a 15 3 15
b 15 14 14
c 13 16 13
d 3 13 15
Series.map has an additional feature which is that it can be used to easily “link” or “map” values defined by a secondary series. This is closely related to merging/joining functionality:
In [97]: s = Series(['six', 'seven', 'six', 'seven', 'six'],
....: index=['a', 'b', 'c', 'd', 'e'])
....:
In [98]: t = Series({'six' : 6., 'seven' : 7.})
In [99]: s
Out[99]:
a six
b seven
c six
d seven
e six
In [100]: s.map(t)
Out[100]:
a 6
b 7
c 6
d 7
e 6
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 [101]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [102]: s
Out[102]:
a -0.296043
b -0.437766
c 0.528272
d -0.020866
e -1.700601
In [103]: s.reindex(['e', 'b', 'f', 'd'])
Out[103]:
e -1.700601
b -0.437766
f NaN
d -0.020866
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 [104]: df
Out[104]:
one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218
In [105]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
Out[105]:
three two one
c -0.090511 0.432798 2.759265
f NaN NaN NaN
b 0.701067 0.985676 -0.412959
For convenience, you may utilize the reindex_axis method, which takes the labels and a keyword axis parameter.
Note that the Index objects containing the actual axis labels can be shared between objects. So if we have a Series and a DataFrame, the following can be done:
In [106]: rs = s.reindex(df.index)
In [107]: rs
Out[107]:
a -0.296043
b -0.437766
c 0.528272
d -0.020866
In [108]: rs.index is df.index
Out[108]: True
This means that the reindexed Series’s index is the same Python object as the DataFrame’s index.
See also
Advanced indexing is an even more concise way of doing reindexing.
Note
When writing performance-sensitive code, there is a good reason to spend some time becoming a reindexing ninja: many operations are faster on pre-aligned data. Adding two unaligned DataFrames internally triggers a reindexing step. For exploratory analysis you will hardly notice the difference (because reindex has been heavily optimized), but when CPU cycles matter sprinking 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 [109]: df
Out[109]:
one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218
In [110]: df2
Out[110]:
one two
a -1.362447 -0.592729
b -0.904889 0.572804
c 2.267336 0.019925
In [111]: df.reindex_like(df2)
Out[111]:
one two
a -0.870517 -0.179856
b -0.412959 0.985676
c 2.759265 0.432798
Reindexing with reindex_axis¶
Aligning objects with each other with align¶
The align method is the fastest way to simultaneously align two objects. It supports a join argument (related to joining and merging):
- join='outer': take the union of the indexes
- join='left': use the calling object’s index
- join='right': use the passed object’s index
- join='inner': intersect the indexes
It returns a tuple with both of the reindexed Series:
In [112]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [113]: s1 = s[:4]
In [114]: s2 = s[1:]
In [115]: s1.align(s2)
Out[115]:
(a -0.361985
b 1.287984
c 0.188743
d -2.446139
e NaN,
a NaN
b 1.287984
c 0.188743
d -2.446139
e -0.478270)
In [116]: s1.align(s2, join='inner')
Out[116]:
(b 1.287984
c 0.188743
d -2.446139,
b 1.287984
c 0.188743
d -2.446139)
In [117]: s1.align(s2, join='left')
Out[117]:
(a -0.361985
b 1.287984
c 0.188743
d -2.446139,
a NaN
b 1.287984
c 0.188743
d -2.446139)
For DataFrames, the join method will be applied to both the index and the columns by default:
In [118]: df.align(df2, join='inner')
Out[118]:
( one two
a -0.870517 -0.179856
b -0.412959 0.985676
c 2.759265 0.432798,
one two
a -1.362447 -0.592729
b -0.904889 0.572804
c 2.267336 0.019925)
You can also pass an axis option to only align on the specified axis:
In [119]: df.align(df2, join='inner', axis=0)
Out[119]:
( one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798,
one two
a -1.362447 -0.592729
b -0.904889 0.572804
c 2.267336 0.019925)
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 [120]: df.align(df2.ix[0], axis=1)
Out[120]:
( one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218,
one -1.362447
three NaN
two -0.592729
Name: a)
Filling while reindexing¶
reindex takes an optional parameter method which is a filling method chosen from the following table:
Method | Action |
---|---|
pad / ffill | Fill values forward |
bfill / backfill | Fill values backward |
Other fill methods could be added, of course, but these are the two most commonly used for time series data. In a way they only make sense for time series or otherwise ordered data, but you may have an application on non-time series data where this sort of “interpolation” logic is the correct thing to do. More sophisticated interpolation of missing values would be an obvious extension.
We illustrate these fill methods on a simple TimeSeries:
In [121]: rng = date_range('1/3/2000', periods=8)
In [122]: ts = Series(randn(8), index=rng)
In [123]: ts2 = ts[[0, 3, 6]]
In [124]: ts
Out[124]:
2000-01-03 -0.973722
2000-01-04 -0.743799
2000-01-05 -0.514520
2000-01-06 1.202940
2000-01-07 2.073680
2000-01-08 -1.218284
2000-01-09 1.494972
2000-01-10 0.230865
Freq: D
In [125]: ts2
Out[125]:
2000-01-03 -0.973722
2000-01-06 1.202940
2000-01-09 1.494972
In [126]: ts2.reindex(ts.index)
Out[126]:
2000-01-03 -0.973722
2000-01-04 NaN
2000-01-05 NaN
2000-01-06 1.202940
2000-01-07 NaN
2000-01-08 NaN
2000-01-09 1.494972
2000-01-10 NaN
Freq: D
In [127]: ts2.reindex(ts.index, method='ffill')
Out[127]:
2000-01-03 -0.973722
2000-01-04 -0.973722
2000-01-05 -0.973722
2000-01-06 1.202940
2000-01-07 1.202940
2000-01-08 1.202940
2000-01-09 1.494972
2000-01-10 1.494972
Freq: D
In [128]: ts2.reindex(ts.index, method='bfill')
Out[128]:
2000-01-03 -0.973722
2000-01-04 1.202940
2000-01-05 1.202940
2000-01-06 1.202940
2000-01-07 1.494972
2000-01-08 1.494972
2000-01-09 1.494972
2000-01-10 NaN
Freq: D
Note the same result could have been achieved using fillna:
In [129]: ts2.reindex(ts.index).fillna(method='ffill')
Out[129]:
2000-01-03 -0.973722
2000-01-04 -0.973722
2000-01-05 -0.973722
2000-01-06 1.202940
2000-01-07 1.202940
2000-01-08 1.202940
2000-01-09 1.494972
2000-01-10 1.494972
Freq: D
Note these methods generally assume that the indexes are sorted. They may be modified in the future to be a bit more flexible but as time series data is ordered most of the time anyway, this has not been a major priority.
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 [130]: df
Out[130]:
one three two
a -0.870517 NaN -0.179856
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
d NaN 0.985138 -0.540218
In [131]: df.drop(['a', 'd'], axis=0)
Out[131]:
one three two
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
In [132]: df.drop(['one'], axis=1)
Out[132]:
three two
a NaN -0.179856
b 0.701067 0.985676
c -0.090511 0.432798
d 0.985138 -0.540218
Note that the following also works, but is a bit less obvious / clean:
In [133]: df.reindex(df.index - ['a', 'd'])
Out[133]:
one three two
b -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
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 [134]: s
Out[134]:
a -0.361985
b 1.287984
c 0.188743
d -2.446139
e -0.478270
In [135]: s.rename(str.upper)
Out[135]:
A -0.361985
B 1.287984
C 0.188743
D -2.446139
E -0.478270
If you pass a function, it must return a value when called with any of the labels (and must produce a set of unique values). But if you pass a dict or Series, it need only contain a subset of the labels as keys:
In [136]: df.rename(columns={'one' : 'foo', 'two' : 'bar'},
.....: index={'a' : 'apple', 'b' : 'banana', 'd' : 'durian'})
.....:
Out[136]:
foo three bar
apple -0.870517 NaN -0.179856
banana -0.412959 0.701067 0.985676
c 2.759265 -0.090511 0.432798
durian NaN 0.985138 -0.540218
The rename method also provides an inplace named parameter that is by default False and copies the underlying data. Pass inplace=True to rename the data in place.
The Panel class has a related rename_axis class which can rename any of its three axes.
Iteration¶
Because Series is array-like, basic iteration produces the values. Other data structures follow the dict-like convention of iterating over the “keys” of the objects. In short:
- Series: values
- DataFrame: column labels
- Panel: item labels
Thus, for example:
In [137]: for col in df:
.....: print col
.....:
one
three
two
iteritems¶
Consistent with the dict-like interface, iteritems iterates through key-value pairs:
- Series: (index, scalar value) pairs
- DataFrame: (column, Series) pairs
- Panel: (item, DataFrame) pairs
For example:
In [138]: for item, frame in wp.iteritems():
.....: print item
.....: print frame
.....:
Item1
A B C D
2000-01-01 0.637062 0.235990 0.588114 0.405520
2000-01-02 0.563153 0.259248 -0.023878 0.645297
2000-01-03 -0.478302 0.158210 -0.627965 -0.717968
2000-01-04 1.831759 0.302368 -0.112629 1.112259
2000-01-05 -0.690172 0.210464 -1.226446 0.414738
Item2
A B C D
2000-01-01 -1.655212 -0.344358 1.140400 -0.225359
2000-01-02 -0.246238 -0.631267 1.018045 -1.068059
2000-01-03 -0.173927 -0.877534 -1.036643 -0.951455
2000-01-04 0.867100 1.597059 -0.190735 0.161550
2000-01-05 0.324506 -0.185006 -1.075707 0.819424
iterrows¶
New in v0.7 is the ability to iterate efficiently through rows of a DataFrame. It returns an iterator yielding each index value along with a Series containing the data in each row:
In [139]: for row_index, row in df2.iterrows():
.....: print '%s\n%s' % (row_index, row)
.....:
a
one -1.362447
two -0.592729
Name: a
b
one -0.904889
two 0.572804
Name: b
c
one 2.267336
two 0.019925
Name: c
For instance, a contrived way to transpose the dataframe would be:
In [140]: df2 = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
In [141]: print df2
x y
0 1 4
1 2 5
2 3 6
In [142]: print df2.T
0 1 2
x 1 2 3
y 4 5 6
In [143]: df2_t = DataFrame(dict((idx,values) for idx, values in df2.iterrows()))
In [144]: print df2_t
0 1 2
x 1 2 3
y 4 5 6
itertuples¶
This method will return an iterator yielding a tuple for each row in the DataFrame. The first element of the tuple will be the row’s corresponding index value, while the remaining values are the row values proper.
For instance,
In [145]: for r in df2.itertuples(): print r
(0, 1, 4)
(1, 2, 5)
(2, 3, 6)
Vectorized string methods¶
Series is equipped (as of pandas 0.8.1) with a set of string processing methods that make it easy to operate on each element of the array. Perhaps most importantly, these methods exclude missing/NA values automatically. These are accessed via the Series’s str attribute and generally have names matching the equivalent (scalar) build-in string methods:
In [146]: s = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
In [147]: s.str.lower()
Out[147]:
0 a
1 b
2 c
3 aaba
4 baca
5 NaN
6 caba
7 dog
8 cat
In [148]: s.str.upper()
Out[148]:
0 A
1 B
2 C
3 AABA
4 BACA
5 NaN
6 CABA
7 DOG
8 CAT
In [149]: s.str.len()
Out[149]:
0 1
1 1
2 1
3 4
4 4
5 NaN
6 4
7 3
8 3
Methods like split return a Series of lists:
In [150]: s2 = Series(['a_b_c', 'c_d_e', np.nan, 'f_g_h'])
In [151]: s2.str.split('_')
Out[151]:
0 ['a', 'b', 'c']
1 ['c', 'd', 'e']
2 NaN
3 ['f', 'g', 'h']
Elements in the split lists can be accessed using get or [] notation:
In [152]: s2.str.split('_').str.get(1)
Out[152]:
0 b
1 d
2 NaN
3 g
In [153]: s2.str.split('_').str[1]
Out[153]:
0 b
1 d
2 NaN
3 g
Methods like replace and findall take regular expressions, too:
In [154]: s3 = Series(['A', 'B', 'C', 'Aaba', 'Baca',
.....: '', np.nan, 'CABA', 'dog', 'cat'])
.....:
In [155]: s3
Out[155]:
0 A
1 B
2 C
3 Aaba
4 Baca
5
6 NaN
7 CABA
8 dog
9 cat
In [156]: s3.str.replace('^.a|dog', 'XX-XX ', case=False)
Out[156]:
0 A
1 B
2 C
3 XX-XX ba
4 XX-XX ca
5
6 NaN
7 XX-XX BA
8 XX-XX
9 XX-XX t
Methods like contains, startswith, and endswith takes an extra na arguement so missing values can be considered True or False:
In [157]: s4 = Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
In [158]: s4.str.contains('A', na=False)
Out[158]:
0 True
1 False
2 False
3 True
4 False
5 NaN
6 True
7 False
8 False
Method | Description |
---|---|
cat | Concatenate strings |
split | Split strings on delimiter |
get | Index into each element (retrieve i-th element) |
join | Join strings in each element of the Series with passed separator |
contains | Return boolean array if each string contains pattern/regex |
replace | Replace occurrences of pattern/regex with some other string |
repeat | Duplicate values (s.str.repeat(3) equivalent to x * 3) |
pad | Add whitespace to left, right, or both sides of strings |
center | Equivalent to pad(side='both') |
slice | Slice each string in the Series |
slice_replace | Replace slice in each string with passed value |
count | Count occurrences of pattern |
startswith | Equivalent to str.startswith(pat) for each element |
endswidth | Equivalent to str.endswith(pat) for each element |
findall | Compute list of all occurrences of pattern/regex for each string |
match | Call re.match on each element, returning matched groups as list |
len | Compute string lengths |
strip | Equivalent to str.strip |
rstrip | Equivalent to str.rstrip |
lstrip | Equivalent to str.lstrip |
lower | Equivalent to str.lower |
upper | Equivalent to str.upper |
Sorting by index and value¶
There are two obvious kinds of sorting that you may be interested in: sorting by label and sorting by actual values. The primary method for sorting axis labels (indexes) across data structures is the sort_index method.
In [159]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
.....: columns=['three', 'two', 'one'])
.....:
In [160]: unsorted_df.sort_index()
Out[160]:
three two one
a NaN -0.179856 -0.870517
b 0.701067 0.985676 -0.412959
c -0.090511 0.432798 2.759265
d 0.985138 -0.540218 NaN
In [161]: unsorted_df.sort_index(ascending=False)
Out[161]:
three two one
d 0.985138 -0.540218 NaN
c -0.090511 0.432798 2.759265
b 0.701067 0.985676 -0.412959
a NaN -0.179856 -0.870517
In [162]: unsorted_df.sort_index(axis=1)
Out[162]:
one three two
a -0.870517 NaN -0.179856
d NaN 0.985138 -0.540218
c 2.759265 -0.090511 0.432798
b -0.412959 0.701067 0.985676
DataFrame.sort_index can accept an optional by argument for axis=0 which will use an arbitrary vector or a column name of the DataFrame to determine the sort order:
In [163]: df.sort_index(by='two')
Out[163]:
one three two
d NaN 0.985138 -0.540218
a -0.870517 NaN -0.179856
c 2.759265 -0.090511 0.432798
b -0.412959 0.701067 0.985676
The by argument can take a list of column names, e.g.:
In [164]: df = DataFrame({'one':[2,1,1,1],'two':[1,3,2,4],'three':[5,4,3,2]})
In [165]: df[['one', 'two', 'three']].sort_index(by=['one','two'])
Out[165]:
one two three
2 1 2 3
1 1 3 4
3 1 4 2
0 2 1 5
Series has the method order (analogous to R’s order function) which sorts by value, with special treatment of NA values via the na_last argument:
In [166]: s[2] = np.nan
In [167]: s.order()
Out[167]:
0 A
3 Aaba
1 B
4 Baca
6 CABA
8 cat
7 dog
2 NaN
5 NaN
In [168]: s.order(na_last=False)
Out[168]:
2 NaN
5 NaN
0 A
3 Aaba
1 B
4 Baca
6 CABA
8 cat
7 dog
Some other sorting notes / nuances:
- Series.sort sorts a Series by value in-place. This is to provide compatibility with NumPy methods which expect the ndarray.sort behavior.
- DataFrame.sort takes a column argument instead of by. This method will likely be deprecated in a future release in favor of just using sort_index.
Copying, type casting¶
The copy method on pandas objects copies the underlying data (though not the axis indexes, since they are immutable) and returns a new object. Note that it is seldom necessary to copy objects. For example, there are only a handful of ways to alter a DataFrame in-place:
- Inserting, deleting, or modifying a column
- Assigning to the index or columns attributes
- For homogeneous data, directly modifying the values via the values attribute or advanced indexing
To be clear, no pandas methods have the side effect of modifying your data; almost all methods return new objects, leaving the original object untouched. If data is modified, it is because you did so explicitly.
Data can be explicitly cast to a NumPy dtype by using the astype method or alternately passing the dtype keyword argument to the object constructor.
In [169]: df = DataFrame(np.arange(12).reshape((4, 3)))
In [170]: df[0].dtype
Out[170]: dtype('int64')
In [171]: df.astype(float)[0].dtype
Out[171]: dtype('float64')
In [172]: df = DataFrame(np.arange(12).reshape((4, 3)), dtype=float)
In [173]: df[0].dtype
Out[173]: dtype('float64')
Inferring better types for object columns¶
The convert_objects DataFrame method will attempt to convert dtype=object columns to a better NumPy dtype. Occasionally (after transposing multiple times, for example), a mixed-type DataFrame will end up with everything as dtype=object. This method attempts to fix that:
In [174]: df = DataFrame(randn(6, 3), columns=['a', 'b', 'c'])
In [175]: df['d'] = 'foo'
In [176]: df
Out[176]:
a b c d
0 1.571052 -0.374771 -0.903639 foo
1 -0.303380 0.823377 -1.180293 foo
2 0.614131 -0.135688 0.166819 foo
3 0.143633 0.245816 -1.239073 foo
4 -0.202816 -2.011053 -0.858282 foo
5 1.197840 -1.321993 1.550186 foo
In [177]: df = df.T.T
In [178]: df.dtypes
Out[178]:
a object
b object
c object
d object
In [179]: converted = df.convert_objects()
In [180]: converted.dtypes
Out[180]:
a float64
b float64
c float64
d object
Pickling and serialization¶
All pandas objects are equipped with save methods which use Python’s cPickle module to save data structures to disk using the pickle format.
In [181]: df
Out[181]:
a b c d
0 1.571052 -0.3747709 -0.9036394 foo
1 -0.3033799 0.8233775 -1.180293 foo
2 0.6141313 -0.1356879 0.1668194 foo
3 0.1436326 0.2458164 -1.239073 foo
4 -0.2028159 -2.011053 -0.8582823 foo
5 1.19784 -1.321993 1.550186 foo
In [182]: df.save('foo.pickle')
The load function in the pandas namespace can be used to load any pickled pandas object (or any other pickled object) from file:
In [183]: load('foo.pickle')
Out[183]:
a b c d
0 1.571052 -0.3747709 -0.9036394 foo
1 -0.3033799 0.8233775 -1.180293 foo
2 0.6141313 -0.1356879 0.1668194 foo
3 0.1436326 0.2458164 -1.239073 foo
4 -0.2028159 -2.011053 -0.8582823 foo
5 1.19784 -1.321993 1.550186 foo
There is also a save function which takes any object as its first argument:
In [184]: save(df, 'foo.pickle')
In [185]: load('foo.pickle')
Out[185]:
a b c d
0 1.571052 -0.3747709 -0.9036394 foo
1 -0.3033799 0.8233775 -1.180293 foo
2 0.6141313 -0.1356879 0.1668194 foo
3 0.1436326 0.2458164 -1.239073 foo
4 -0.2028159 -2.011053 -0.8582823 foo
5 1.19784 -1.321993 1.550186 foo
Console Output Formatting¶
Use the set_eng_float_format function in the pandas.core.common module to alter the floating-point formatting of pandas objects to produce a particular format.
For instance:
In [186]: set_eng_float_format(accuracy=3, use_eng_prefix=True)
In [187]: df['a']/1.e3
Out[187]:
0 1.571m
1 -303.380u
2 614.131u
3 143.633u
4 -202.816u
5 1.198m
Name: a
In [188]: df['a']/1.e6
Out[188]:
0 1.571u
1 -303.380n
2 614.131n
3 143.633n
4 -202.816n
5 1.198u
Name: a
The set_printoptions function has a number of options for controlling how floating point numbers are formatted (using hte precision argument) in the console and . The max_rows and max_columns control how many rows and columns of DataFrame objects are shown by default. If max_columns is set to 0 (the default, in fact), the library will attempt to fit the DataFrame’s string representation into the current terminal width, and defaulting to the summary view otherwise.