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 = DateRange('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=DateRange('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.395255
1 -0.632260
2 0.173969
3 1.320848
4 0.226964
In [7]: long_series.tail(3)
Out[7]:
997 -1.005834
998 1.125063
999 0.222895
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-03 -0.214829 -0.142451 -0.282057
2000-01-04 0.864059 -0.608186 1.536483
In [9]: df.columns = [x.lower() for x in df.columns]
In [10]: df
Out[10]:
a b c
2000-01-03 -0.214829 -0.142451 -0.282057
2000-01-04 0.864059 -0.608186 1.536483
2000-01-05 -0.872287 -0.659650 -0.661710
2000-01-06 -0.091525 1.075137 -0.882660
2000-01-07 -1.621064 -0.773457 -0.770732
2000-01-10 0.974817 -0.166694 -0.727561
2000-01-11 0.308386 0.320270 -2.061148
2000-01-12 -1.740628 -0.222302 0.172190
To get the actual data inside a data structure, one need only access the values property:
In [11]: s.values
Out[11]: array([-0.4585, -1.8419, 0.0322, 0.0218, -0.9995])
In [12]: df.values
Out[12]:
array([[-0.2148, -0.1425, -0.2821],
[ 0.8641, -0.6082, 1.5365],
[-0.8723, -0.6596, -0.6617],
[-0.0915, 1.0751, -0.8827],
[-1.6211, -0.7735, -0.7707],
[ 0.9748, -0.1667, -0.7276],
[ 0.3084, 0.3203, -2.0611],
[-1.7406, -0.2223, 0.1722]])
In [13]: wp.values
Out[13]:
array([[[ 0.8383, 1.6071, -1.7119, -0.2156],
[-1.4868, -0.187 , -0.9808, 1.6427],
[ 0.7641, 0.4294, 1.2497, 0.5067],
[ 0.7656, -2.4271, -1.2652, -0.5706],
[ 1.7256, -1.5106, -0.5281, 0.5593]],
[[-2.1587, 0.4519, 1.4765, -0.9683],
[-0.0549, 0.2323, 0.7039, -0.1495],
[ 0.2353, -0.6546, 1.5889, -0.7716],
[ 0.108 , 2.4888, 2.325 , 0.688 ],
[ 0.0614, -0.3168, -0.2638, -0.0902]]])
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 -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650
In [15]: row = df.ix[1]
In [16]: column = df['two']
In [17]: df.sub(row, axis='columns')
Out[17]:
one three two
a -1.670205 NaN 0.770434
b 0.000000 0.000000 0.000000
c 1.050451 -3.231782 0.182734
d NaN -2.074872 -0.669178
In [18]: df.sub(row, axis=1)
Out[18]:
one three two
a -1.670205 NaN 0.770434
b 0.000000 0.000000 0.000000
c 1.050451 -3.231782 0.182734
d NaN -2.074872 -0.669178
In [19]: df.sub(column, axis='index')
Out[19]:
one three two
a -2.725523 NaN 0
b -0.284885 2.153404 0
c 0.582831 -1.261113 0
d NaN 0.747709 0
In [20]: df.sub(column, axis=0)
Out[20]:
one three two
a -2.725523 NaN 0
b -0.284885 2.153404 0
c 0.582831 -1.261113 0
d NaN 0.747709 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.521348 -0.361771
B -0.417654 0.440338
C -0.647243 1.166107
D 0.384496 -0.258330
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-03 00:00:00 to 2000-01-07 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 -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650
In [25]: df2
Out[25]:
one three two
a -1.803562 1.000000 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650
In [26]: df + df2
Out[26]:
one three two
a -3.607123 NaN 1.843923
b -0.266714 4.609863 0.303055
c 1.834187 -1.853702 0.668524
d NaN 0.460118 -1.035300
In [27]: df.add(df2, fill_value=0)
Out[27]:
one three two
a -3.607123 1.000000 1.843923
b -0.266714 4.609863 0.303055
c 1.834187 -1.853702 0.668524
d NaN 0.460118 -1.035300
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 [28]: df1 = DataFrame({'A' : [1., np.nan, 3., 5., np.nan],
....: 'B' : [np.nan, 2., 3., np.nan, 6.]})
In [29]: df2 = DataFrame({'A' : [5., 2., 4., np.nan, 3., 7.],
....: 'B' : [np.nan, np.nan, 3., 4., 6., 8.]})
In [30]: df1
Out[30]:
A B
0 1 NaN
1 NaN 2
2 3 3
3 5 NaN
4 NaN 6
In [31]: df2
Out[31]:
A B
0 5 NaN
1 2 NaN
2 4 3
3 NaN 4
4 3 6
5 7 8
In [32]: df1.combine_first(df2)
Out[32]:
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 [33]: combiner = lambda x, y: np.where(isnull(x), y, x)
In [34]: df1.combine(df2, combiner)
Out[34]:
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 [35]: df
Out[35]:
one three two
a -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650
In [36]: df.mean(0)
Out[36]:
one -0.339942
three 0.536047
two 0.222525
In [37]: df.mean(1)
Out[37]:
a -0.440800
b 0.774367
c 0.108168
d -0.143796
All such methods have a skipna option signaling whether to exclude missing data (True by default):
In [38]: df.sum(0, skipna=False)
Out[38]:
one NaN
three NaN
two 0.890101
In [39]: df.sum(axis=1, skipna=True)
Out[39]:
a -0.881600
b 2.323102
c 0.324505
d -0.287591
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 [40]: ts_stand = (df - df.mean()) / df.std()
In [41]: ts_stand.std()
Out[41]:
one 1
three 1
two 1
In [42]: xs_stand = df.sub(df.mean(1), axis=0).div(df.std(1), axis=0)
In [43]: xs_stand.std(1)
Out[43]:
a 1
b 1
c 1
d 1
Note that methods like cumsum and cumprod preserve the location of NA values:
In [44]: df.cumsum()
Out[44]:
one three two
a -1.803562 NaN 0.921961
b -1.936919 2.304932 1.073489
c -1.019825 1.378081 1.407751
d NaN 1.608140 0.890101
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 [45]: np.mean(df['one'])
Out[45]: -0.33994174173412101
In [46]: np.mean(df['one'].values)
Out[46]: nan
Series also has a method nunique which will return the number of unique non-null values:
In [47]: series = Series(randn(500))
In [48]: series[20:500] = np.nan
In [49]: series[10:20] = 5
In [50]: series.nunique()
Out[50]: 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 [51]: series = Series(randn(1000))
In [52]: series[::2] = np.nan
In [53]: series.describe()
Out[53]:
count 500.000000
mean -0.022562
std 1.016534
min -3.909767
25% -0.695256
50% -0.026351
75% 0.655005
max 2.818375
In [54]: frame = DataFrame(randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])
In [55]: frame.ix[::2] = np.nan
In [56]: frame.describe()
Out[56]:
a b c d e
count 500.000000 500.000000 500.000000 500.000000 500.000000
mean 0.087006 0.016977 0.002514 0.064459 0.047516
std 1.010381 1.028309 1.003938 0.982985 1.029576
min -3.033923 -3.186314 -2.650052 -2.754301 -3.504149
25% -0.581764 -0.653484 -0.713372 -0.595791 -0.638621
50% 0.105008 0.031949 -0.052945 0.031084 0.050620
75% 0.754432 0.724837 0.709446 0.710579 0.725168
max 3.082986 2.666830 2.879336 3.065742 3.151635
For a non-numerical Series object, describe will give a simple summary of the number of unique values and most frequently occurring values:
In [57]: s = Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])
In [58]: s.describe()
Out[58]:
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 [59]: s1 = Series(randn(5))
In [60]: s1
Out[60]:
0 1.408007
1 -0.650623
2 -0.750666
3 0.013871
4 1.246326
In [61]: s1.idxmin(), s1.idxmax()
Out[61]: (2, 0)
In [62]: df1 = DataFrame(randn(5,3), columns=['A','B','C'])
In [63]: df1
Out[63]:
A B C
0 -0.105404 -0.665238 0.470341
1 -1.140010 0.842451 1.362074
2 -0.300080 -0.188657 0.066332
3 -0.441389 -1.186129 -0.535485
4 0.173416 0.192418 -0.647838
In [64]: df1.idxmin(axis=0)
Out[64]:
A 1
B 3
C 4
In [65]: df1.idxmax(axis=1)
Out[65]:
0 C
1 C
2 C
3 A
4 B
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 [66]: df.apply(np.mean)
Out[66]:
one -0.339942
three 0.536047
two 0.222525
In [67]: df.apply(np.mean, axis=1)
Out[67]:
a -0.440800
b 0.774367
c 0.108168
d -0.143796
In [68]: df.apply(lambda x: x.max() - x.min())
Out[68]:
one 2.720655
three 3.231782
two 1.439612
In [69]: df.apply(np.cumsum)
Out[69]:
one three two
a -1.803562 NaN 0.921961
b -1.936919 2.304932 1.073489
c -1.019825 1.378081 1.407751
d NaN 1.608140 0.890101
In [70]: df.apply(np.exp)
Out[70]:
one three two
a 0.164711 NaN 2.514217
b 0.875153 10.023492 1.163610
c 2.502008 0.395798 1.396909
d NaN 1.258674 0.595919
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 [71]: tsdf = DataFrame(randn(1000, 3), columns=['A', 'B', 'C'],
....: index=DateRange('1/1/2000', periods=1000))
In [72]: tsdf.apply(lambda x: x.index[x.dropna().argmax()])
Out[72]:
A 2003-04-23 00:00:00
B 2003-09-05 00:00:00
C 2000-06-15 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 [73]: tsdf
Out[73]:
A B C
2000-01-03 0.220295 0.027538 -0.643213
2000-01-04 -0.216840 -0.077551 1.760229
2000-01-05 0.354672 -0.869926 -1.838944
2000-01-06 NaN NaN NaN
2000-01-07 NaN NaN NaN
2000-01-10 NaN NaN NaN
2000-01-11 NaN NaN NaN
2000-01-12 1.072984 2.086809 0.707775
2000-01-13 0.791807 -0.757370 -0.234677
2000-01-14 -1.481734 -0.724198 1.839899
In [74]: tsdf.apply(Series.interpolate)
Out[74]:
A B C
2000-01-03 0.220295 0.027538 -0.643213
2000-01-04 -0.216840 -0.077551 1.760229
2000-01-05 0.354672 -0.869926 -1.838944
2000-01-06 0.498335 -0.278579 -1.329600
2000-01-07 0.641997 0.312768 -0.820256
2000-01-10 0.785659 0.904115 -0.310912
2000-01-11 0.929321 1.495462 0.198432
2000-01-12 1.072984 2.086809 0.707775
2000-01-13 0.791807 -0.757370 -0.234677
2000-01-14 -1.481734 -0.724198 1.839899
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 [75]: f = lambda x: len(str(x))
In [76]: df['one'].map(f)
Out[76]:
a 14
b 15
c 14
d 3
Name: one
In [77]: df.applymap(f)
Out[77]:
one three two
a 14 3 13
b 15 13 14
c 14 15 14
d 3 14 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 [78]: s = Series(['six', 'seven', 'six', 'seven', 'six'],
....: index=['a', 'b', 'c', 'd', 'e'])
In [79]: t = Series({'six' : 6., 'seven' : 7.})
In [80]: s
Out[80]:
a six
b seven
c six
d seven
e six
In [81]: s.map(t)
Out[81]:
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 [82]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [83]: s
Out[83]:
a -0.559624
b 1.008419
c 1.626928
d 0.692417
e 0.452548
In [84]: s.reindex(['e', 'b', 'f', 'd'])
Out[84]:
e 0.452548
b 1.008419
f NaN
d 0.692417
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 [85]: df
Out[85]:
one three two
a -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650
In [86]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
Out[86]:
three two one
c -0.926851 0.334262 0.917093
f NaN NaN NaN
b 2.304932 0.151528 -0.133357
For convenience, you may utilize the reindex_axis method, which takes the labels and a keyword axis paramater.
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 [87]: rs = s.reindex(df.index)
In [88]: rs
Out[88]:
a -0.559624
b 1.008419
c 1.626928
d 0.692417
In [89]: rs.index is df.index
Out[89]: 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 [90]: df
Out[90]:
one three two
a -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650
In [91]: df2
Out[91]:
one two
a -1.463620 0.452711
b 0.206585 -0.317723
c 1.257035 -0.134988
In [92]: df.reindex_like(df2)
Out[92]:
one two
a -1.803562 0.921961
b -0.133357 0.151528
c 0.917093 0.334262
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 [93]: s = Series(randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [94]: s1 = s[:4]
In [95]: s2 = s[1:]
In [96]: s1.align(s2)
Out[96]:
(a 1.125606
b -0.426032
c -0.061063
d -0.644590
e NaN,
a NaN
b -0.426032
c -0.061063
d -0.644590
e 1.551388)
In [97]: s1.align(s2, join='inner')
Out[97]:
(b -0.426032
c -0.061063
d -0.644590,
b -0.426032
c -0.061063
d -0.644590)
In [98]: s1.align(s2, join='left')
Out[98]:
(a 1.125606
b -0.426032
c -0.061063
d -0.644590,
a NaN
b -0.426032
c -0.061063
d -0.644590)
For DataFrames, the join method will be applied to both the index and the columns by default:
In [99]: df.align(df2, join='inner')
Out[99]:
( one two
a -1.803562 0.921961
b -0.133357 0.151528
c 0.917093 0.334262,
one two
a -1.463620 0.452711
b 0.206585 -0.317723
c 1.257035 -0.134988)
You can also pass an axis option to only align on the specified axis:
In [100]: df.align(df2, join='inner', axis=0)
Out[100]:
( one three two
a -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262,
one two
a -1.463620 0.452711
b 0.206585 -0.317723
c 1.257035 -0.134988)
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 [101]: df.align(df2.ix[0], axis=1)
Out[101]:
( one three two
a -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650,
one -1.463620
three NaN
two 0.452711
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 [102]: rng = DateRange('1/3/2000', periods=8)
In [103]: ts = Series(randn(8), index=rng)
In [104]: ts2 = ts[[0, 3, 6]]
In [105]: ts
Out[105]:
2000-01-03 -0.759826
2000-01-04 1.154537
2000-01-05 -0.199039
2000-01-06 -0.261202
2000-01-07 0.041710
2000-01-10 -0.476623
2000-01-11 -0.725007
2000-01-12 -0.432569
In [106]: ts2
Out[106]:
2000-01-03 -0.759826
2000-01-06 -0.261202
2000-01-11 -0.725007
In [107]: ts2.reindex(ts.index)
Out[107]:
2000-01-03 -0.759826
2000-01-04 NaN
2000-01-05 NaN
2000-01-06 -0.261202
2000-01-07 NaN
2000-01-10 NaN
2000-01-11 -0.725007
2000-01-12 NaN
In [108]: ts2.reindex(ts.index, method='ffill')
Out[108]:
2000-01-03 -0.759826
2000-01-04 -0.759826
2000-01-05 -0.759826
2000-01-06 -0.261202
2000-01-07 -0.261202
2000-01-10 -0.261202
2000-01-11 -0.725007
2000-01-12 -0.725007
In [109]: ts2.reindex(ts.index, method='bfill')
Out[109]:
2000-01-03 -0.759826
2000-01-04 -0.261202
2000-01-05 -0.261202
2000-01-06 -0.261202
2000-01-07 -0.725007
2000-01-10 -0.725007
2000-01-11 -0.725007
2000-01-12 NaN
Note the same result could have been achieved using fillna:
In [110]: ts2.reindex(ts.index).fillna(method='ffill')
Out[110]:
2000-01-03 -0.759826
2000-01-04 -0.759826
2000-01-05 -0.759826
2000-01-06 -0.261202
2000-01-07 -0.261202
2000-01-10 -0.261202
2000-01-11 -0.725007
2000-01-12 -0.725007
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 [111]: df
Out[111]:
one three two
a -1.803562 NaN 0.921961
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
d NaN 0.230059 -0.517650
In [112]: df.drop(['a', 'd'], axis=0)
Out[112]:
one three two
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
In [113]: df.drop(['one'], axis=1)
Out[113]:
three two
a NaN 0.921961
b 2.304932 0.151528
c -0.926851 0.334262
d 0.230059 -0.517650
Note that the following also works, but a bit less obvious / clean:
In [114]: df.reindex(df.index - ['a', 'd'])
Out[114]:
one three two
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
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 [115]: s
Out[115]:
a 1.125606
b -0.426032
c -0.061063
d -0.644590
e 1.551388
In [116]: s.rename(str.upper)
Out[116]:
A 1.125606
B -0.426032
C -0.061063
D -0.644590
E 1.551388
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 [117]: df.rename(columns={'one' : 'foo', 'two' : 'bar'},
.....: index={'a' : 'apple', 'b' : 'banana', 'd' : 'durian'})
Out[117]:
foo three bar
apple -1.803562 NaN 0.921961
banana -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
durian NaN 0.230059 -0.517650
The rename method also provides a copy named parameter that is by default True and copies the underlying data. Pass copy=False to rename the data in place.
The Panel class has an a related rename_axis class which can rename any of its three axes.
Iteration¶
Considering the pandas as somewhat dict-like structure, basic iteration produces the “keys” of the objects, namely:
- Series: the index label
- DataFrame: the column labels
- Panel: the item labels
Thus, for example:
In [118]: 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 [119]: for item, frame in wp.iteritems():
.....: print item
.....: print frame
.....:
Item1
A B C D
2000-01-03 0.838258 1.607060 -1.711896 -0.215590
2000-01-04 -1.486802 -0.186982 -0.980778 1.642659
2000-01-05 0.764063 0.429431 1.249702 0.506673
2000-01-06 0.765594 -2.427144 -1.265159 -0.570580
2000-01-07 1.725629 -1.510635 -0.528086 0.559317
Item2
A B C D
2000-01-03 -2.158684 0.451897 1.476465 -0.968314
2000-01-04 -0.054924 0.232306 0.703899 -0.149485
2000-01-05 0.235345 -0.654572 1.588949 -0.771629
2000-01-06 0.107966 2.488819 2.324974 0.687952
2000-01-07 0.061444 -0.316759 -0.263752 -0.090173
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 [120]: for row_index, row in df2.iterrows():
.....: print '%s\n%s' % (row_index, row)
.....:
a
one -1.463620
two 0.452711
Name: a
b
one 0.206585
two -0.317723
Name: b
c
one 1.257035
two -0.134988
Name: c
For instance, a contrived way to transpose the dataframe would be:
In [121]: df2 = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
In [122]: print df2
x y
0 1 4
1 2 5
2 3 6
In [123]: print df2.T
0 1 2
x 1 2 3
y 4 5 6
In [124]: df2_t = DataFrame(dict((idx,values) for idx, values in df2.iterrows()))
In [125]: 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 [126]: for r in df2.itertuples(): print r
(0, 1, 4)
(1, 2, 5)
(2, 3, 6)
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 [127]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
.....: columns=['three', 'two', 'one'])
In [128]: unsorted_df.sort_index()
Out[128]:
three two one
a NaN 0.921961 -1.803562
b 2.304932 0.151528 -0.133357
c -0.926851 0.334262 0.917093
d 0.230059 -0.517650 NaN
In [129]: unsorted_df.sort_index(ascending=False)
Out[129]:
three two one
d 0.230059 -0.517650 NaN
c -0.926851 0.334262 0.917093
b 2.304932 0.151528 -0.133357
a NaN 0.921961 -1.803562
In [130]: unsorted_df.sort_index(axis=1)
Out[130]:
one three two
a -1.803562 NaN 0.921961
d NaN 0.230059 -0.517650
c 0.917093 -0.926851 0.334262
b -0.133357 2.304932 0.151528
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 [131]: df.sort_index(by='two')
Out[131]:
one three two
d NaN 0.230059 -0.517650
b -0.133357 2.304932 0.151528
c 0.917093 -0.926851 0.334262
a -1.803562 NaN 0.921961
The by argument can take a list of column names, e.g.:
In [132]: df = DataFrame({'one':[2,1,1,1],'two':[1,3,2,4],'three':[5,4,3,2]})
In [133]: df[['one', 'two', 'three']].sort_index(by=['one','two'])
Out[133]:
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 [134]: s[2] = np.nan
In [135]: s.order()
Out[135]:
d -0.644590
b -0.426032
a 1.125606
e 1.551388
c NaN
In [136]: s.order(na_last=False)
Out[136]:
c NaN
d -0.644590
b -0.426032
a 1.125606
e 1.551388
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 [137]: df = DataFrame(np.arange(12).reshape((4, 3)))
In [138]: df[0].dtype
Out[138]: dtype('int64')
In [139]: df.astype(float)[0].dtype
Out[139]: dtype('float64')
In [140]: df = DataFrame(np.arange(12).reshape((4, 3)), dtype=float)
In [141]: df[0].dtype
Out[141]: 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 [142]: df = DataFrame(randn(6, 3), columns=['a', 'b', 'c'])
In [143]: df['d'] = 'foo'
In [144]: df
Out[144]:
a b c d
0 -0.455471 0.031559 -0.099764 foo
1 -0.700640 -1.481563 1.759569 foo
2 0.108328 -0.601951 0.540880 foo
3 0.035645 0.249108 -0.715238 foo
4 0.674059 1.026316 -0.983394 foo
5 -0.819144 -1.939507 -1.617302 foo
In [145]: df = df.T.T
In [146]: df.dtypes
Out[146]:
a object
b object
c object
d object
In [147]: converted = df.convert_objects()
In [148]: converted.dtypes
Out[148]:
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 [149]: df
Out[149]:
a b c d
0 -0.4554712 0.03155879 -0.09976363 foo
1 -0.7006397 -1.481563 1.759569 foo
2 0.1083282 -0.6019514 0.5408803 foo
3 0.03564486 0.2491077 -0.7152381 foo
4 0.6740586 1.026316 -0.9833944 foo
5 -0.8191439 -1.939507 -1.617302 foo
In [150]: 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 [151]: load('foo.pickle')
Out[151]:
a b c d
0 -0.4554712 0.03155879 -0.09976363 foo
1 -0.7006397 -1.481563 1.759569 foo
2 0.1083282 -0.6019514 0.5408803 foo
3 0.03564486 0.2491077 -0.7152381 foo
4 0.6740586 1.026316 -0.9833944 foo
5 -0.8191439 -1.939507 -1.617302 foo
There is also a save function which takes any object as its first argument:
In [152]: save(df, 'foo.pickle')
In [153]: load('foo.pickle')
Out[153]:
a b c d
0 -0.4554712 0.03155879 -0.09976363 foo
1 -0.7006397 -1.481563 1.759569 foo
2 0.1083282 -0.6019514 0.5408803 foo
3 0.03564486 0.2491077 -0.7152381 foo
4 0.6740586 1.026316 -0.9833944 foo
5 -0.8191439 -1.939507 -1.617302 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 [154]: set_eng_float_format(accuracy=3, use_eng_prefix=True)
In [155]: df['a']/1.e3
Out[155]:
0 -455.471u
1 -700.640u
2 108.328u
3 35.645u
4 674.059u
5 -819.144u
Name: a
In [156]: df['a']/1.e6
Out[156]:
0 -455.471n
1 -700.640n
2 108.328n
3 35.645n
4 674.059n
5 -819.144n
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.