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 -1.130476
1 -2.338072
2 1.070626
3 -0.139699
4 1.193558
In [7]: long_series.tail(3)
Out[7]:
997 -0.182799
998 -0.196688
999 -1.376285
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.723322 -0.371889 0.094834
2000-01-04 -0.369412 -1.032963 0.781797
In [9]: df.columns = [x.lower() for x in df.columns]
In [10]: df
Out[10]:
a b c
2000-01-03 -0.723322 -0.371889 0.094834
2000-01-04 -0.369412 -1.032963 0.781797
2000-01-05 -0.502693 -0.292891 0.262744
2000-01-06 -0.755828 -0.026536 0.633955
2000-01-07 -0.776066 -0.526272 0.518514
2000-01-10 0.366056 0.233639 -1.655289
2000-01-11 -0.310129 -1.028230 0.622798
2000-01-12 0.346898 -0.563376 0.577713
To get the actual data inside a data structure, one need only access the values property:
In [11]: s.values
Out[11]: array([ 1.8251, -0.4597, -0.9565, -0.7855, -0.2558])
In [12]: df.values
Out[12]:
array([[-0.7233, -0.3719, 0.0948],
[-0.3694, -1.033 , 0.7818],
[-0.5027, -0.2929, 0.2627],
[-0.7558, -0.0265, 0.634 ],
[-0.7761, -0.5263, 0.5185],
[ 0.3661, 0.2336, -1.6553],
[-0.3101, -1.0282, 0.6228],
[ 0.3469, -0.5634, 0.5777]])
In [13]: wp.values
Out[13]:
array([[[ 1.8089, 1.4334, -0.0242, 0.4675],
[ 0.253 , -0.9784, -0.6741, 0.4518],
[-0.827 , 0.2282, -0.5838, -0.2402],
[ 0.66 , 0.2153, 0.1941, 0.5852],
[-1.0802, 0.2295, -0.5472, 1.0192]],
[[-0.1907, -1.041 , 0.5897, 0.088 ],
[ 1.5311, 0.4984, -0.6075, 0.6598],
[-0.5374, 2.0488, 0.3283, 0.4507],
[-0.1766, 0.2128, 0.9568, -0.95 ],
[-2.7901, 0.8421, 0.9888, 0.701 ]]])
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300
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.791908 NaN -0.631509
b 0.000000 0.000000 0.000000
c 1.796433 0.145898 2.047038
d NaN 1.043293 -0.496764
In [18]: df.sub(row, axis=1)
Out[18]:
one three two
a 1.791908 NaN -0.631509
b 0.000000 0.000000 0.000000
c 1.796433 0.145898 2.047038
d NaN 1.043293 -0.496764
In [19]: df.sub(column, axis='index')
Out[19]:
one three two
a 1.789320 NaN 0
b -0.634096 -0.226845 0
c -0.884702 -2.127985 0
d NaN 1.313212 0
In [20]: df.sub(column, axis=0)
Out[20]:
one three two
a 1.789320 NaN 0
b -0.634096 -0.226845 0
c -0.884702 -2.127985 0
d NaN 1.313212 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.162930 -0.432753
B 0.225589 0.512237
C -0.327036 0.451222
D 0.456688 0.189883
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300
In [25]: df2
Out[25]:
one three two
a 1.315276 1.000000 -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300
In [26]: df + df2
Out[26]:
one three two
a 2.630552 NaN -0.948089
b -0.953264 -0.138762 0.314929
c 2.639601 0.153035 4.409005
d NaN 1.947824 -0.678600
In [27]: df.add(df2, fill_value=0)
Out[27]:
one three two
a 2.630552 1.000000 -0.948089
b -0.953264 -0.138762 0.314929
c 2.639601 0.153035 4.409005
d NaN 1.947824 -0.678600
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300
In [36]: df.mean(0)
Out[36]:
one 0.719481
three 0.327016
two 0.387156
In [37]: df.mean(1)
Out[37]:
a 0.420616
b -0.129516
c 1.200274
d 0.317306
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 1.548623
In [39]: df.sum(axis=1, skipna=True)
Out[39]:
a 0.841231
b -0.388549
c 3.600821
d 0.634612
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.315276 NaN -0.474045
b 0.838644 -0.069381 -0.316580
c 2.158444 0.007136 1.887923
d NaN 0.981048 1.548623
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.71948146017250103
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.037914
std 0.982343
min -3.008976
25% -0.628684
50% -0.032744
75% 0.597255
max 2.584235
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.018083 0.002895 0.038669 0.052438 -0.054448
std 0.975464 0.993644 1.045549 1.011899 1.036582
min -3.081442 -2.620890 -2.811813 -2.729194 -3.050600
25% -0.752856 -0.708619 -0.644085 -0.620958 -0.665659
50% 0.000519 0.054674 0.032333 0.017732 -0.032307
75% 0.724951 0.658668 0.714194 0.710375 0.570252
max 2.806759 3.181581 2.989046 2.709945 3.844977
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 0.608672
1 -1.034511
2 0.433680
3 -0.578459
4 -0.473016
In [61]: s1.idxmin(), s1.idxmax()
Out[61]: (1, 0)
In [62]: df1 = DataFrame(randn(5,3), columns=['A','B','C'])
In [63]: df1
Out[63]:
A B C
0 2.540358 -0.143648 2.002690
1 0.669421 -0.354109 0.237133
2 -2.459650 0.214558 -0.565066
3 0.744164 1.255754 0.041664
4 0.425022 0.049945 -0.466555
In [64]: df1.idxmin(axis=0)
Out[64]:
A 2
B 1
C 2
In [65]: df1.idxmax(axis=1)
Out[65]:
0 A
1 A
2 B
3 B
4 A
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.719481
three 0.327016
two 0.387156
In [67]: df.apply(np.mean, axis=1)
Out[67]:
a 0.420616
b -0.129516
c 1.200274
d 0.317306
In [68]: df.apply(lambda x: x.max() - x.min())
Out[68]:
one 1.796433
three 1.043293
two 2.678547
In [69]: df.apply(np.cumsum)
Out[69]:
one three two
a 1.315276 NaN -0.474045
b 0.838644 -0.069381 -0.316580
c 2.158444 0.007136 1.887923
d NaN 0.981048 1.548623
In [70]: df.apply(np.exp)
Out[70]:
one three two
a 3.725779 NaN 0.622480
b 0.620871 0.932971 1.170539
c 3.742675 1.079521 9.065742
d NaN 2.648284 0.712269
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 2000-03-31 00:00:00
B 2001-02-02 00:00:00
C 2001-03-23 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.239879 -0.178291 0.487268
2000-01-04 -1.227233 -1.267504 1.446579
2000-01-05 0.036887 0.435839 1.516929
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 0.208174 1.260682 -1.481652
2000-01-13 0.017150 0.936579 0.881074
2000-01-14 -0.460098 0.610600 -0.231508
In [74]: tsdf.apply(Series.interpolate)
Out[74]:
A B C
2000-01-03 0.239879 -0.178291 0.487268
2000-01-04 -1.227233 -1.267504 1.446579
2000-01-05 0.036887 0.435839 1.516929
2000-01-06 0.071144 0.600808 0.917213
2000-01-07 0.105402 0.765776 0.317497
2000-01-10 0.139659 0.930745 -0.282220
2000-01-11 0.173917 1.095713 -0.881936
2000-01-12 0.208174 1.260682 -1.481652
2000-01-13 0.017150 0.936579 0.881074
2000-01-14 -0.460098 0.610600 -0.231508
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 13
b 15
c 13
d 3
Name: one
In [77]: df.applymap(f)
Out[77]:
one three two
a 13 3 15
b 15 16 14
c 13 14 13
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.081110
b 1.958399
c -0.231891
d 0.822924
e -0.536176
In [84]: s.reindex(['e', 'b', 'f', 'd'])
Out[84]:
e -0.536176
b 1.958399
f NaN
d 0.822924
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300
In [86]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
Out[86]:
three two one
c 0.076517 2.204503 1.319801
f NaN NaN NaN
b -0.069381 0.157464 -0.476632
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.081110
b 1.958399
c -0.231891
d 0.822924
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300
In [91]: df2
Out[91]:
one two
a 0.595794 -1.103352
b -1.196114 -0.471843
c 0.600319 1.575195
In [92]: df.reindex_like(df2)
Out[92]:
one two
a 1.315276 -0.474045
b -0.476632 0.157464
c 1.319801 2.204503
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 0.885379
b 0.340164
c -0.201135
d -0.120146
e NaN,
a NaN
b 0.340164
c -0.201135
d -0.120146
e -1.302308)
In [97]: s1.align(s2, join='inner')
Out[97]:
(b 0.340164
c -0.201135
d -0.120146,
b 0.340164
c -0.201135
d -0.120146)
In [98]: s1.align(s2, join='left')
Out[98]:
(a 0.885379
b 0.340164
c -0.201135
d -0.120146,
a NaN
b 0.340164
c -0.201135
d -0.120146)
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.315276 -0.474045
b -0.476632 0.157464
c 1.319801 2.204503,
one two
a 0.595794 -1.103352
b -1.196114 -0.471843
c 0.600319 1.575195)
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503,
one two
a 0.595794 -1.103352
b -1.196114 -0.471843
c 0.600319 1.575195)
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300,
one 0.595794
three NaN
two -1.103352
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.860946
2000-01-04 -0.907973
2000-01-05 -0.295678
2000-01-06 -0.294099
2000-01-07 -1.915930
2000-01-10 0.679769
2000-01-11 1.280126
2000-01-12 1.147501
In [106]: ts2
Out[106]:
2000-01-03 0.860946
2000-01-06 -0.294099
2000-01-11 1.280126
In [107]: ts2.reindex(ts.index)
Out[107]:
2000-01-03 0.860946
2000-01-04 NaN
2000-01-05 NaN
2000-01-06 -0.294099
2000-01-07 NaN
2000-01-10 NaN
2000-01-11 1.280126
2000-01-12 NaN
In [108]: ts2.reindex(ts.index, method='ffill')
Out[108]:
2000-01-03 0.860946
2000-01-04 0.860946
2000-01-05 0.860946
2000-01-06 -0.294099
2000-01-07 -0.294099
2000-01-10 -0.294099
2000-01-11 1.280126
2000-01-12 1.280126
In [109]: ts2.reindex(ts.index, method='bfill')
Out[109]:
2000-01-03 0.860946
2000-01-04 -0.294099
2000-01-05 -0.294099
2000-01-06 -0.294099
2000-01-07 1.280126
2000-01-10 1.280126
2000-01-11 1.280126
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.860946
2000-01-04 0.860946
2000-01-05 0.860946
2000-01-06 -0.294099
2000-01-07 -0.294099
2000-01-10 -0.294099
2000-01-11 1.280126
2000-01-12 1.280126
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.315276 NaN -0.474045
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
d NaN 0.973912 -0.339300
In [112]: df.drop(['a', 'd'], axis=0)
Out[112]:
one three two
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
In [113]: df.drop(['one'], axis=1)
Out[113]:
three two
a NaN -0.474045
b -0.069381 0.157464
c 0.076517 2.204503
d 0.973912 -0.339300
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.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
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 0.885379
b 0.340164
c -0.201135
d -0.120146
e -1.302308
In [116]: s.rename(str.upper)
Out[116]:
A 0.885379
B 0.340164
C -0.201135
D -0.120146
E -1.302308
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.315276 NaN -0.474045
banana -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
durian NaN 0.973912 -0.339300
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 1.808881 1.433414 -0.024171 0.467520
2000-01-04 0.252985 -0.978388 -0.674097 0.451778
2000-01-05 -0.827043 0.228164 -0.583827 -0.240240
2000-01-06 0.660048 0.215303 0.194092 0.585210
2000-01-07 -1.080220 0.229454 -0.547179 1.019172
Item2
A B C D
2000-01-03 -0.190726 -1.040995 0.589679 0.087983
2000-01-04 1.531085 0.498421 -0.607503 0.659753
2000-01-05 -0.537430 2.048803 0.328332 0.450698
2000-01-06 -0.176605 0.212841 0.956847 -0.950002
2000-01-07 -2.790089 0.842116 0.988757 0.700983
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 0.595794
two -1.103352
Name: a
b
one -1.196114
two -0.471843
Name: b
c
one 0.600319
two 1.575195
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.474045 1.315276
b -0.069381 0.157464 -0.476632
c 0.076517 2.204503 1.319801
d 0.973912 -0.339300 NaN
In [129]: unsorted_df.sort_index(ascending=False)
Out[129]:
three two one
d 0.973912 -0.339300 NaN
c 0.076517 2.204503 1.319801
b -0.069381 0.157464 -0.476632
a NaN -0.474045 1.315276
In [130]: unsorted_df.sort_index(axis=1)
Out[130]:
one three two
a 1.315276 NaN -0.474045
d NaN 0.973912 -0.339300
c 1.319801 0.076517 2.204503
b -0.476632 -0.069381 0.157464
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
a 1.315276 NaN -0.474045
d NaN 0.973912 -0.339300
b -0.476632 -0.069381 0.157464
c 1.319801 0.076517 2.204503
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]:
e -1.302308
d -0.120146
b 0.340164
a 0.885379
c NaN
In [136]: s.order(na_last=False)
Out[136]:
c NaN
e -1.302308
d -0.120146
b 0.340164
a 0.885379
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 -1.678000 0.316271 -0.764522 foo
1 -2.408878 0.214938 -0.145975 foo
2 0.491452 -0.384245 -1.006620 foo
3 0.221259 -2.261983 -0.662206 foo
4 -0.266302 0.595202 0.957032 foo
5 1.577024 -1.523379 1.869230 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 -1.678 0.3162712 -0.7645219 foo
1 -2.408878 0.2149379 -0.1459749 foo
2 0.4914522 -0.3842448 -1.00662 foo
3 0.2212592 -2.261983 -0.6622059 foo
4 -0.2663019 0.5952018 0.9570319 foo
5 1.577024 -1.523379 1.86923 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 -1.678 0.3162712 -0.7645219 foo
1 -2.408878 0.2149379 -0.1459749 foo
2 0.4914522 -0.3842448 -1.00662 foo
3 0.2212592 -2.261983 -0.6622059 foo
4 -0.2663019 0.5952018 0.9570319 foo
5 1.577024 -1.523379 1.86923 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 -1.678 0.3162712 -0.7645219 foo
1 -2.408878 0.2149379 -0.1459749 foo
2 0.4914522 -0.3842448 -1.00662 foo
3 0.2212592 -2.261983 -0.6622059 foo
4 -0.2663019 0.5952018 0.9570319 foo
5 1.577024 -1.523379 1.86923 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 -1.678m
1 -2.409m
2 491.452u
3 221.259u
4 -266.302u
5 1.577m
Name: a
In [156]: df['a']/1.e6
Out[156]:
0 -1.678u
1 -2.409u
2 491.452n
3 221.259n
4 -266.302n
5 1.577u
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.