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.401750
1 0.629207
2 1.490369
3 -0.100855
4 0.517183
In [7]: long_series.tail(3)
Out[7]:
997 1.908308
998 0.121918
999 -0.317150
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.717191 1.788361 -0.509708
2000-01-04 -0.139546 -0.064465 -0.302006
In [9]: df.columns = [x.lower() for x in df.columns]
In [10]: df
Out[10]:
a b c
2000-01-03 0.717191 1.788361 -0.509708
2000-01-04 -0.139546 -0.064465 -0.302006
2000-01-05 -0.261477 0.246761 0.274933
2000-01-06 0.744685 0.252769 1.709227
2000-01-07 -0.385984 1.162372 -1.073196
2000-01-10 1.195949 0.063138 0.376171
2000-01-11 0.867389 -0.114348 -0.123580
2000-01-12 -1.483158 -1.197809 -1.350483
To get the actual data inside a data structure, one need only access the values property:
In [11]: s.values
Out[11]: array([ 1.4356, -1.2892, -0.8717, -0.7001, 2.3788])
In [12]: df.values
Out[12]:
array([[ 0.7172, 1.7884, -0.5097],
[-0.1395, -0.0645, -0.302 ],
[-0.2615, 0.2468, 0.2749],
[ 0.7447, 0.2528, 1.7092],
[-0.386 , 1.1624, -1.0732],
[ 1.1959, 0.0631, 0.3762],
[ 0.8674, -0.1143, -0.1236],
[-1.4832, -1.1978, -1.3505]])
In [13]: wp.values
Out[13]:
array([[[-2.0588, -1.9974, -0.3285, 0.9758],
[-1.0602, -1.1869, 1.1671, 0.9451],
[-0.3642, -1.8626, -0.0437, 0.3068],
[ 0.6776, 0.9243, -1.1807, -0.4986],
[ 1.2911, 1.215 , 1.6184, 0.1671]],
[[-0.1112, 0.2799, 1.5191, 0.0685],
[-0.4144, 0.447 , 1.6341, -1.3137],
[ 0.6895, -0.0252, -2.187 , 0.8882],
[-2.888 , -0.8931, -1.4021, 1.4791],
[ 0.3438, -0.8136, -0.6102, 0.1197]]])
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.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
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.318532 NaN 1.253106
b 0.000000 0.000000 0.000000
c 0.004918 -2.070768 -0.520598
d NaN -1.462914 -0.337963
In [18]: df.sub(row, axis=1)
Out[18]:
one three two
a 0.318532 NaN 1.253106
b 0.000000 0.000000 0.000000
c 0.004918 -2.070768 -0.520598
d NaN -1.462914 -0.337963
In [19]: df.sub(column, axis='index')
Out[19]:
one three two
a -0.542852 NaN 0
b 0.391721 0.631556 0
c 0.917237 -0.918614 0
d NaN -0.493396 0
In [20]: df.sub(column, axis=0)
Out[20]:
one three two
a -0.542852 NaN 0
b 0.391721 0.631556 0
c 0.917237 -0.918614 0
d NaN -0.493396 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.302885 -0.476036
B -0.581546 -0.200996
C 0.246514 -0.209203
D 0.379236 0.248353
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 0.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
In [25]: df2
Out[25]:
one three two
a 0.734281 1.000000 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
In [26]: df + df2
Out[26]:
one three two
a 1.468562 NaN 2.554266
b 0.831498 1.311167 0.048055
c 0.841334 -2.830369 -0.993140
d NaN -1.614662 -0.627870
In [27]: df.add(df2, fill_value=0)
Out[27]:
one three two
a 1.468562 1.000000 2.554266
b 0.831498 1.311167 0.048055
c 0.841334 -2.830369 -0.993140
d NaN -1.614662 -0.627870
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 0.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
In [36]: df.mean(0)
Out[36]:
one 0.523566
three -0.522311
two 0.122664
In [37]: df.mean(1)
Out[37]:
a 1.005707
b 0.365120
c -0.497029
d -0.560633
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.490656
In [39]: df.sum(axis=1, skipna=True)
Out[39]:
a 2.011414
b 1.095360
c -1.491088
d -1.121266
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 0.734281 NaN 1.277133
b 1.150030 0.655583 1.301161
c 1.570697 -0.759601 0.804591
d NaN -1.566932 0.490656
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.52356564767166136
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.031495
std 0.973570
min -2.897084
25% -0.656922
50% 0.067701
75% 0.739883
max 2.975183
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.062213 0.003731 0.046795 -0.053951 -0.045388
std 1.018215 0.989550 0.973680 0.999438 1.012499
min -2.786115 -2.704258 -2.772261 -3.481377 -3.359114
25% -0.730431 -0.675349 -0.597633 -0.747187 -0.684501
50% -0.093029 0.019079 0.020983 -0.027073 -0.070026
75% 0.577450 0.733066 0.639112 0.654627 0.684203
max 3.171019 2.610121 2.895631 2.719146 3.559090
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.319327
1 0.412872
2 1.498795
3 -0.233211
4 -0.482670
In [61]: s1.idxmin(), s1.idxmax()
Out[61]: (4, 2)
In [62]: df1 = DataFrame(randn(5,3), columns=['A','B','C'])
In [63]: df1
Out[63]:
A B C
0 -0.473931 1.591848 2.003392
1 -0.968043 0.028562 -0.677992
2 0.322633 0.465099 -1.701310
3 -1.724594 0.409119 1.231914
4 0.518751 0.535558 0.970702
In [64]: df1.idxmin(axis=0)
Out[64]:
A 3
B 1
C 2
In [65]: df1.idxmax(axis=1)
Out[65]:
0 C
1 B
2 B
3 C
4 C
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.523566
three -0.522311
two 0.122664
In [67]: df.apply(np.mean, axis=1)
Out[67]:
a 1.005707
b 0.365120
c -0.497029
d -0.560633
In [68]: df.apply(lambda x: x.max() - x.min())
Out[68]:
one 0.318532
three 2.070768
two 1.773703
In [69]: df.apply(np.cumsum)
Out[69]:
one three two
a 0.734281 NaN 1.277133
b 1.150030 0.655583 1.301161
c 1.570697 -0.759601 0.804591
d NaN -1.566932 0.490656
In [70]: df.apply(np.exp)
Out[70]:
one three two
a 2.083983 NaN 3.586344
b 1.515506 1.926266 1.024319
c 1.522977 0.242881 0.608615
d NaN 0.446047 0.730567
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 2001-05-28 00:00:00
B 2002-05-06 00:00:00
C 2002-01-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 1.278618 -1.838926 1.573421
2000-01-04 -0.247793 0.042045 0.381821
2000-01-05 -0.217078 0.228790 0.433500
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.041985 0.345333 1.501663
2000-01-13 1.535773 -0.764237 0.034943
2000-01-14 0.915595 0.347488 1.312351
In [74]: tsdf.apply(Series.interpolate)
Out[74]:
A B C
2000-01-03 1.278618 -1.838926 1.573421
2000-01-04 -0.247793 0.042045 0.381821
2000-01-05 -0.217078 0.228790 0.433500
2000-01-06 -0.182059 0.252098 0.647132
2000-01-07 -0.147041 0.275407 0.860765
2000-01-10 -0.112022 0.298716 1.074398
2000-01-11 -0.077004 0.322024 1.288030
2000-01-12 -0.041985 0.345333 1.501663
2000-01-13 1.535773 -0.764237 0.034943
2000-01-14 0.915595 0.347488 1.312351
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 14
c 14
d 3
Name: one
In [77]: df.applymap(f)
Out[77]:
one three two
a 14 3 13
b 14 14 14
c 14 14 15
d 3 15 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.994568
b 0.726056
c -0.888537
d -0.248802
e 0.088887
In [84]: s.reindex(['e', 'b', 'f', 'd'])
Out[84]:
e 0.088887
b 0.726056
f NaN
d -0.248802
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 0.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
In [86]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
Out[86]:
three two one
c -1.415184 -0.496570 0.420667
f NaN NaN NaN
b 0.655583 0.024028 0.415749
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.994568
b 0.726056
c -0.888537
d -0.248802
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 0.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
In [91]: df2
Out[91]:
one two
a 0.210715 1.008936
b -0.107817 -0.244169
c -0.102899 -0.764767
In [92]: df.reindex_like(df2)
Out[92]:
one two
a 0.734281 1.277133
b 0.415749 0.024028
c 0.420667 -0.496570
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.715032
b -0.685681
c 0.001675
d -0.828261
e NaN,
a NaN
b -0.685681
c 0.001675
d -0.828261
e -1.220265)
In [97]: s1.align(s2, join='inner')
Out[97]:
(b -0.685681
c 0.001675
d -0.828261,
b -0.685681
c 0.001675
d -0.828261)
In [98]: s1.align(s2, join='left')
Out[98]:
(a -1.715032
b -0.685681
c 0.001675
d -0.828261,
a NaN
b -0.685681
c 0.001675
d -0.828261)
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 0.734281 1.277133
b 0.415749 0.024028
c 0.420667 -0.496570,
one two
a 0.210715 1.008936
b -0.107817 -0.244169
c -0.102899 -0.764767)
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 0.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570,
one two
a 0.210715 1.008936
b -0.107817 -0.244169
c -0.102899 -0.764767)
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 0.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935,
one 0.210715
three NaN
two 1.008936
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.642211
2000-01-04 -1.241115
2000-01-05 -1.290155
2000-01-06 0.609739
2000-01-07 -0.417950
2000-01-10 0.174421
2000-01-11 0.334299
2000-01-12 -1.309011
In [106]: ts2
Out[106]:
2000-01-03 -0.642211
2000-01-06 0.609739
2000-01-11 0.334299
In [107]: ts2.reindex(ts.index)
Out[107]:
2000-01-03 -0.642211
2000-01-04 NaN
2000-01-05 NaN
2000-01-06 0.609739
2000-01-07 NaN
2000-01-10 NaN
2000-01-11 0.334299
2000-01-12 NaN
In [108]: ts2.reindex(ts.index, method='ffill')
Out[108]:
2000-01-03 -0.642211
2000-01-04 -0.642211
2000-01-05 -0.642211
2000-01-06 0.609739
2000-01-07 0.609739
2000-01-10 0.609739
2000-01-11 0.334299
2000-01-12 0.334299
In [109]: ts2.reindex(ts.index, method='bfill')
Out[109]:
2000-01-03 -0.642211
2000-01-04 0.609739
2000-01-05 0.609739
2000-01-06 0.609739
2000-01-07 0.334299
2000-01-10 0.334299
2000-01-11 0.334299
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.642211
2000-01-04 -0.642211
2000-01-05 -0.642211
2000-01-06 0.609739
2000-01-07 0.609739
2000-01-10 0.609739
2000-01-11 0.334299
2000-01-12 0.334299
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 0.734281 NaN 1.277133
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
In [112]: df.drop(['a', 'd'], axis=0)
Out[112]:
one three two
b 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
In [113]: df.drop(['one'], axis=1)
Out[113]:
three two
a NaN 1.277133
b 0.655583 0.024028
c -1.415184 -0.496570
d -0.807331 -0.313935
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.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
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.715032
b -0.685681
c 0.001675
d -0.828261
e -1.220265
In [116]: s.rename(str.upper)
Out[116]:
A -1.715032
B -0.685681
C 0.001675
D -0.828261
E -1.220265
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 0.734281 NaN 1.277133
banana 0.415749 0.655583 0.024028
c 0.420667 -1.415184 -0.496570
durian NaN -0.807331 -0.313935
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 -2.058758 -1.997433 -0.328472 0.975796
2000-01-04 -1.060204 -1.186923 1.167138 0.945111
2000-01-05 -0.364170 -1.862606 -0.043733 0.306757
2000-01-06 0.677599 0.924252 -1.180747 -0.498589
2000-01-07 1.291109 1.214983 1.618382 0.167105
Item2
A B C D
2000-01-03 -0.111166 0.279881 1.519107 0.068480
2000-01-04 -0.414434 0.447046 1.634123 -1.313698
2000-01-05 0.689533 -0.025200 -2.186983 0.888209
2000-01-06 -2.887960 -0.893092 -1.402067 1.479112
2000-01-07 0.343849 -0.813614 -0.610196 0.119664
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.210715
two 1.008936
Name: a
b
one -0.107817
two -0.244169
Name: b
c
one -0.102899
two -0.764767
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
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 [126]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
.....: columns=['three', 'two', 'one'])
In [127]: unsorted_df.sort_index()
Out[127]:
three two one
a NaN 1.277133 0.734281
b 0.655583 0.024028 0.415749
c -1.415184 -0.496570 0.420667
d -0.807331 -0.313935 NaN
In [128]: unsorted_df.sort_index(ascending=False)
Out[128]:
three two one
d -0.807331 -0.313935 NaN
c -1.415184 -0.496570 0.420667
b 0.655583 0.024028 0.415749
a NaN 1.277133 0.734281
In [129]: unsorted_df.sort_index(axis=1)
Out[129]:
one three two
a 0.734281 NaN 1.277133
d NaN -0.807331 -0.313935
c 0.420667 -1.415184 -0.496570
b 0.415749 0.655583 0.024028
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 [130]: df.sort_index(by='two')
Out[130]:
one three two
c 0.420667 -1.415184 -0.496570
d NaN -0.807331 -0.313935
b 0.415749 0.655583 0.024028
a 0.734281 NaN 1.277133
The by argument can take a list of column names, e.g.:
In [131]: df = DataFrame({'one':[2,1,1,1],'two':[1,3,2,4],'three':[5,4,3,2]})
In [132]: df[['one', 'two', 'three']].sort_index(by=['one','two'])
Out[132]:
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 [133]: s[2] = np.nan
In [134]: s.order()
Out[134]:
a -1.715032
e -1.220265
d -0.828261
b -0.685681
c NaN
In [135]: s.order(na_last=False)
Out[135]:
c NaN
a -1.715032
e -1.220265
d -0.828261
b -0.685681
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 [136]: df = DataFrame(np.arange(12).reshape((4, 3)))
In [137]: df[0].dtype
Out[137]: dtype('int64')
In [138]: df.astype(float)[0].dtype
Out[138]: dtype('float64')
In [139]: df = DataFrame(np.arange(12).reshape((4, 3)), dtype=float)
In [140]: df[0].dtype
Out[140]: 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 [141]: df = DataFrame(randn(6, 3), columns=['a', 'b', 'c'])
In [142]: df['d'] = 'foo'
In [143]: df
Out[143]:
a b c d
0 -0.975158 -0.031003 0.420091 foo
1 0.276536 -1.206534 -0.131701 foo
2 0.484504 -0.532560 -0.796278 foo
3 -0.875386 -0.129590 0.824028 foo
4 -0.008612 -1.256263 -0.569521 foo
5 0.224243 0.147046 -0.534953 foo
In [144]: df = df.T.T
In [145]: df.dtypes
Out[145]:
a object
b object
c object
d object
In [146]: converted = df.convert_objects()
In [147]: converted.dtypes
Out[147]:
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 [148]: df
Out[148]:
a b c d
0 -0.9751579 -0.03100335 0.4200913 foo
1 0.2765355 -1.206534 -0.1317013 foo
2 0.4845038 -0.5325605 -0.7962776 foo
3 -0.8753861 -0.1295902 0.8240283 foo
4 -0.008612389 -1.256263 -0.569521 foo
5 0.2242425 0.1470459 -0.5349534 foo
In [149]: 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 [150]: load('foo.pickle')
Out[150]:
a b c d
0 -0.9751579 -0.03100335 0.4200913 foo
1 0.2765355 -1.206534 -0.1317013 foo
2 0.4845038 -0.5325605 -0.7962776 foo
3 -0.8753861 -0.1295902 0.8240283 foo
4 -0.008612389 -1.256263 -0.569521 foo
5 0.2242425 0.1470459 -0.5349534 foo
There is also a save function which takes any object as its first argument:
In [151]: save(df, 'foo.pickle')
In [152]: load('foo.pickle')
Out[152]:
a b c d
0 -0.9751579 -0.03100335 0.4200913 foo
1 0.2765355 -1.206534 -0.1317013 foo
2 0.4845038 -0.5325605 -0.7962776 foo
3 -0.8753861 -0.1295902 0.8240283 foo
4 -0.008612389 -1.256263 -0.569521 foo
5 0.2242425 0.1470459 -0.5349534 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 [153]: set_eng_float_format(accuracy=3, use_eng_prefix=True)
In [154]: df['a']/1.e3
Out[154]:
0 -975.158u
1 276.536u
2 484.504u
3 -875.386u
4 -8.612u
5 224.243u
Name: a
In [155]: df['a']/1.e6
Out[155]:
0 -975.158n
1 276.536n
2 484.504n
3 -875.386n
4 -8.612n
5 224.243n
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.