Indexing and selecting data¶
The axis labeling information in pandas objects serves many purposes:
- Identifies data (i.e. provides metadata) using known indicators, important for for analysis, visualization, and interactive console display
- Enables automatic and explicit data alignment
- Allows intuitive getting and setting of subsets of the data set
In this section / chapter, we will focus on the final point: namely, how to slice, dice, and generally get and set subsets of pandas objects. The primary focus will be on Series and DataFrame as they have received more development attention in this area. Expect more work to be invested higher-dimensional data structures (including Panel) in the future, especially in label-based advanced indexing.
Basics¶
As mentioned when introducing the data structures in the last section, the primary function of indexing with [] (a.k.a. __getitem__ for those familiar with implementing class behavior in Python) is selecting out lower-dimensional slices. Thus,
- Series: series[label] returns a scalar value
- DataFrame: frame[colname] returns a Series corresponding to the passed column name
- Panel: panel[itemname] returns a DataFrame corresponding to the passed item name
Here we construct a simple time series data set to use for illustrating the indexing functionality:
In [542]: dates = np.asarray(date_range('1/1/2000', periods=8))
In [543]: df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
In [544]: df
Out[544]:
A B C D
2000-01-01 0.469112 -0.282863 -1.509059 -1.135632
2000-01-02 1.212112 -0.173215 0.119209 -1.044236
2000-01-03 -0.861849 -2.104569 -0.494929 1.071804
2000-01-04 0.721555 -0.706771 -1.039575 0.271860
2000-01-05 -0.424972 0.567020 0.276232 -1.087401
2000-01-06 -0.673690 0.113648 -1.478427 0.524988
2000-01-07 0.404705 0.577046 -1.715002 -1.039268
2000-01-08 -0.370647 -1.157892 -1.344312 0.844885
In [545]: panel = Panel({'one' : df, 'two' : df - df.mean()})
In [546]: panel
Out[546]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 8 (major) x 4 (minor)
Items: one to two
Major axis: 2000-01-01 00:00:00 to 2000-01-08 00:00:00
Minor axis: A to D
Note
None of the indexing functionality is time series specific unless specifically stated.
Thus, as per above, we have the most basic indexing using []:
In [547]: s = df['A']
In [548]: s[dates[5]]
Out[548]: -0.67368970808837059
In [549]: panel['two']
Out[549]:
A B C D
2000-01-01 0.409571 0.113086 -0.610826 -0.936507
2000-01-02 1.152571 0.222735 1.017442 -0.845111
2000-01-03 -0.921390 -1.708620 0.403304 1.270929
2000-01-04 0.662014 -0.310822 -0.141342 0.470985
2000-01-05 -0.484513 0.962970 1.174465 -0.888276
2000-01-06 -0.733231 0.509598 -0.580194 0.724113
2000-01-07 0.345164 0.972995 -0.816769 -0.840143
2000-01-08 -0.430188 -0.761943 -0.446079 1.044010
Fast scalar value getting and setting¶
Since indexing with [] must handle a lot of cases (single-label access, slicing, boolean indexing, etc.), it has a bit of overhead in order to figure out what you’re asking for. If you only want to access a scalar value, the fastest way is to use the get_value method, which is implemented on all of the data structures:
In [550]: s.get_value(dates[5])
Out[550]: -0.67368970808837059
In [551]: df.get_value(dates[5], 'A')
Out[551]: -0.67368970808837059
There is an analogous set_value method which has the additional capability of enlarging an object. This method always returns a reference to the object it modified, which in the fast of enlargement, will be a new object:
In [552]: df.set_value(dates[5], 'E', 7)
Out[552]:
A B C D E
2000-01-01 0.469112 -0.282863 -1.509059 -1.135632 NaN
2000-01-02 1.212112 -0.173215 0.119209 -1.044236 NaN
2000-01-03 -0.861849 -2.104569 -0.494929 1.071804 NaN
2000-01-04 0.721555 -0.706771 -1.039575 0.271860 NaN
2000-01-05 -0.424972 0.567020 0.276232 -1.087401 NaN
2000-01-06 -0.673690 0.113648 -1.478427 0.524988 7
2000-01-07 0.404705 0.577046 -1.715002 -1.039268 NaN
2000-01-08 -0.370647 -1.157892 -1.344312 0.844885 NaN
Additional Column Access¶
You may access a column on a dataframe directly as an attribute:
In [553]: df.A
Out[553]:
2000-01-01 0.469112
2000-01-02 1.212112
2000-01-03 -0.861849
2000-01-04 0.721555
2000-01-05 -0.424972
2000-01-06 -0.673690
2000-01-07 0.404705
2000-01-08 -0.370647
Name: A
If you are using the IPython environment, you may also use tab-completion to see the accessible columns of a DataFrame.
You can pass a list of columns to [] to select columns in that order: If a column is not contained in the DataFrame, an exception will be raised. Multiple columns can also be set in this manner:
In [554]: df
Out[554]:
A B C D
2000-01-01 0.469112 -0.282863 -1.509059 -1.135632
2000-01-02 1.212112 -0.173215 0.119209 -1.044236
2000-01-03 -0.861849 -2.104569 -0.494929 1.071804
2000-01-04 0.721555 -0.706771 -1.039575 0.271860
2000-01-05 -0.424972 0.567020 0.276232 -1.087401
2000-01-06 -0.673690 0.113648 -1.478427 0.524988
2000-01-07 0.404705 0.577046 -1.715002 -1.039268
2000-01-08 -0.370647 -1.157892 -1.344312 0.844885
In [555]: df[['B', 'A']] = df[['A', 'B']]
In [556]: df
Out[556]:
A B C D
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632
2000-01-02 -0.173215 1.212112 0.119209 -1.044236
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804
2000-01-04 -0.706771 0.721555 -1.039575 0.271860
2000-01-05 0.567020 -0.424972 0.276232 -1.087401
2000-01-06 0.113648 -0.673690 -1.478427 0.524988
2000-01-07 0.577046 0.404705 -1.715002 -1.039268
2000-01-08 -1.157892 -0.370647 -1.344312 0.844885
You may find this useful for applying a transform (in-place) to a subset of the columns.
Data slices on other axes¶
It’s certainly possible to retrieve data slices along the other axes of a DataFrame or Panel. We tend to refer to these slices as cross-sections. DataFrame has the xs function for retrieving rows as Series and Panel has the analogous major_xs and minor_xs functions for retrieving slices as DataFrames for a given major_axis or minor_axis label, respectively.
In [557]: date = dates[5]
In [558]: df.xs(date)
Out[558]:
A 0.113648
B -0.673690
C -1.478427
D 0.524988
Name: 2000-01-06 00:00:00
In [559]: panel.major_xs(date)
Out[559]:
one two
A -0.673690 -0.733231
B 0.113648 0.509598
C -1.478427 -0.580194
D 0.524988 0.724113
In [560]: panel.minor_xs('A')
Out[560]:
one two
2000-01-01 0.469112 0.409571
2000-01-02 1.212112 1.152571
2000-01-03 -0.861849 -0.921390
2000-01-04 0.721555 0.662014
2000-01-05 -0.424972 -0.484513
2000-01-06 -0.673690 -0.733231
2000-01-07 0.404705 0.345164
2000-01-08 -0.370647 -0.430188
Slicing ranges¶
The most robust and consistent way of slicing ranges along arbitrary axes is described in the Advanced indexing section detailing the .ix method. For now, we explain the semantics of slicing using the [] operator.
With Series, the syntax works exactly as with an ndarray, returning a slice of the values and the corresponding labels:
In [561]: s[:5]
Out[561]:
2000-01-01 -0.282863
2000-01-02 -0.173215
2000-01-03 -2.104569
2000-01-04 -0.706771
2000-01-05 0.567020
Name: A
In [562]: s[::2]
Out[562]:
2000-01-01 -0.282863
2000-01-03 -2.104569
2000-01-05 0.567020
2000-01-07 0.577046
Name: A
In [563]: s[::-1]
Out[563]:
2000-01-08 -1.157892
2000-01-07 0.577046
2000-01-06 0.113648
2000-01-05 0.567020
2000-01-04 -0.706771
2000-01-03 -2.104569
2000-01-02 -0.173215
2000-01-01 -0.282863
Name: A
Note that setting works as well:
In [564]: s2 = s.copy()
In [565]: s2[:5] = 0
In [566]: s2
Out[566]:
2000-01-01 0.000000
2000-01-02 0.000000
2000-01-03 0.000000
2000-01-04 0.000000
2000-01-05 0.000000
2000-01-06 0.113648
2000-01-07 0.577046
2000-01-08 -1.157892
Name: A
With DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.
In [567]: df[:3]
Out[567]:
A B C D
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632
2000-01-02 -0.173215 1.212112 0.119209 -1.044236
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804
In [568]: df[::-1]
Out[568]:
A B C D
2000-01-08 -1.157892 -0.370647 -1.344312 0.844885
2000-01-07 0.577046 0.404705 -1.715002 -1.039268
2000-01-06 0.113648 -0.673690 -1.478427 0.524988
2000-01-05 0.567020 -0.424972 0.276232 -1.087401
2000-01-04 -0.706771 0.721555 -1.039575 0.271860
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804
2000-01-02 -0.173215 1.212112 0.119209 -1.044236
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632
Boolean indexing¶
Another common operation is the use of boolean vectors to filter the data.
Using a boolean vector to index a Series works exactly as in a numpy ndarray:
In [569]: s[s > 0]
Out[569]:
2000-01-05 0.567020
2000-01-06 0.113648
2000-01-07 0.577046
Name: A
In [570]: s[(s < 0) & (s > -0.5)]
Out[570]:
2000-01-01 -0.282863
2000-01-02 -0.173215
Name: A
You may select rows from a DataFrame using a boolean vector the same length as the DataFrame’s index (for example, something derived from one of the columns of the DataFrame):
In [571]: df[df['A'] > 0]
Out[571]:
A B C D
2000-01-05 0.567020 -0.424972 0.276232 -1.087401
2000-01-06 0.113648 -0.673690 -1.478427 0.524988
2000-01-07 0.577046 0.404705 -1.715002 -1.039268
Consider the isin method of Series, which returns a boolean vector that is true wherever the Series elements exist in the passed list. This allows you to select rows where one or more columns have values you want:
In [572]: df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
.....: 'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
.....: 'c' : randn(7)})
.....:
In [573]: df2[df2['a'].isin(['one', 'two'])]
Out[573]:
a b c
0 one x 1.075770
1 one y -0.109050
2 two y 1.643563
4 two y 0.357021
5 one x -0.674600
List comprehensions and map method of Series can also be used to produce more complex criteria:
# only want 'two' or 'three'
In [574]: criterion = df2['a'].map(lambda x: x.startswith('t'))
In [575]: df2[criterion]
Out[575]:
a b c
2 two y 1.643563
3 three x -1.469388
4 two y 0.357021
# equivalent but slower
In [576]: df2[[x.startswith('t') for x in df2['a']]]
Out[576]:
a b c
2 two y 1.643563
3 three x -1.469388
4 two y 0.357021
# Multiple criteria
In [577]: df2[criterion & (df2['b'] == 'x')]
Out[577]:
a b c
3 three x -1.469388
Note, with the advanced indexing ix method, you may select along more than one axis using boolean vectors combined with other indexing expressions.
Indexing a DataFrame with a boolean DataFrame¶
You may wish to set values on a DataFrame based on some boolean criteria derived from itself or another DataFrame or set of DataFrames. This can be done intuitively like so:
In [578]: df2 = df.copy()
In [579]: df2 < 0
Out[579]:
A B C D
2000-01-01 True False True True
2000-01-02 True False False True
2000-01-03 True True True False
2000-01-04 True False True False
2000-01-05 False True False True
2000-01-06 False True True False
2000-01-07 False False True True
2000-01-08 True True True False
In [580]: df2[df2 < 0] = 0
In [581]: df2
Out[581]:
A B C D
2000-01-01 0.000000 0.469112 0.000000 0.000000
2000-01-02 0.000000 1.212112 0.119209 0.000000
2000-01-03 0.000000 0.000000 0.000000 1.071804
2000-01-04 0.000000 0.721555 0.000000 0.271860
2000-01-05 0.567020 0.000000 0.276232 0.000000
2000-01-06 0.113648 0.000000 0.000000 0.524988
2000-01-07 0.577046 0.404705 0.000000 0.000000
2000-01-08 0.000000 0.000000 0.000000 0.844885
Note that such an operation requires that the boolean DataFrame is indexed exactly the same.
Take Methods¶
Similar to numpy ndarrays, pandas Index, Series, and DataFrame also provides the take method that retrieves elements along a given axis at the given indices. The given indices must be either a list or an ndarray of integer index positions.
In [582]: index = Index(randint(0, 1000, 10))
In [583]: index
Out[583]: Int64Index([969, 412, 496, 195, 288, 101, 881, 900, 732, 658])
In [584]: positions = [0, 9, 3]
In [585]: index[positions]
Out[585]: Int64Index([969, 658, 195])
In [586]: index.take(positions)
Out[586]: Int64Index([969, 658, 195])
In [587]: ser = Series(randn(10))
In [588]: ser.ix[positions]
Out[588]:
0 -0.968914
9 -1.131345
3 1.247642
In [589]: ser.take(positions)
Out[589]:
0 -0.968914
9 -1.131345
3 1.247642
For DataFrames, the given indices should be a 1d list or ndarray that specifies row or column positions.
In [590]: frm = DataFrame(randn(5, 3))
In [591]: frm.take([1, 4, 3])
Out[591]:
0 1 2
1 -0.932132 1.956030 0.017587
4 -0.077118 -0.408530 -0.862495
3 -1.143704 0.215897 1.193555
In [592]: frm.take([0, 2], axis=1)
Out[592]:
0 2
0 -0.089329 -0.945867
1 -0.932132 0.017587
2 -0.016692 0.254161
3 -1.143704 1.193555
4 -0.077118 -0.862495
It is important to note that the take method on pandas objects are not intended to work on boolean indices and may return unexpected results.
In [593]: arr = randn(10)
In [594]: arr.take([False, False, True, True])
Out[594]: array([ 1.3461, 1.3461, 1.5118, 1.5118])
In [595]: arr[[0, 1]]
Out[595]: array([ 1.3461, 1.5118])
In [596]: ser = Series(randn(10))
In [597]: ser.take([False, False, True, True])
Out[597]:
0 -0.105381
0 -0.105381
1 -0.532532
1 -0.532532
In [598]: ser.ix[[0, 1]]
Out[598]:
0 -0.105381
1 -0.532532
Finally, as a small note on performance, because the take method handles a narrower range of inputs, it can offer performance that is a good deal faster than fancy indexing.
Duplicate Data¶
If you want to identify and remove duplicate rows in a DataFrame, there are two methods that will help: duplicated and drop_duplicates. Each takes as an argument the columns to use to identify duplicated rows.
duplicated returns a boolean vector whose length is the number of rows, and which indicates whether a row is duplicated.
drop_duplicates removes duplicate rows.
By default, the first observed row of a duplicate set is considered unique, but each method has a take_last parameter that indicates the last observed row should be taken instead.
In [599]: df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
.....: 'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
.....: 'c' : np.random.randn(7)})
.....:
In [600]: df2.duplicated(['a','b'])
Out[600]:
0 False
1 False
2 False
3 False
4 True
5 True
6 False
In [601]: df2.drop_duplicates(['a','b'])
Out[601]:
a b c
0 one x -0.339355
1 one y 0.593616
2 two y 0.884345
3 three x 1.591431
6 six x 0.435589
In [602]: df2.drop_duplicates(['a','b'], take_last=True)
Out[602]:
a b c
1 one y 0.593616
3 three x 1.591431
4 two y 0.141809
5 one x 0.220390
6 six x 0.435589
Dictionary-like get method¶
Each of Series, DataFrame, and Panel have a get method which can return a default value.
In [603]: s = Series([1,2,3], index=['a','b','c'])
In [604]: s.get('a') # equivalent to s['a']
Out[604]: 1
In [605]: s.get('x', default=-1)
Out[605]: -1
Advanced indexing with labels¶
We have avoided excessively overloading the [] / __getitem__ operator to keep the basic functionality of the pandas objects straightforward and simple. However, there are often times when you may wish get a subset (or analogously set a subset) of the data in a way that is not straightforward using the combination of reindex and []. Complicated setting operations are actually quite difficult because reindex usually returns a copy.
By advanced indexing we are referring to a special .ix attribute on pandas objects which enable you to do getting/setting operations on a DataFrame, for example, with matrix/ndarray-like semantics. Thus you can combine the following kinds of indexing:
- An integer or single label, e.g. 5 or 'a'
- A list or array of labels ['a', 'b', 'c'] or integers [4, 3, 0]
- A slice object with ints 1:7 or labels 'a':'f'
- A boolean array
We’ll illustrate all of these methods. First, note that this provides a concise way of reindexing on multiple axes at once:
In [606]: subindex = dates[[3,4,5]]
In [607]: df.reindex(index=subindex, columns=['C', 'B'])
Out[607]:
C B
2000-01-04 -1.039575 0.721555
2000-01-05 0.276232 -0.424972
2000-01-06 -1.478427 -0.673690
In [608]: df.ix[subindex, ['C', 'B']]
Out[608]:
C B
2000-01-04 -1.039575 0.721555
2000-01-05 0.276232 -0.424972
2000-01-06 -1.478427 -0.673690
Assignment / setting values is possible when using ix:
In [609]: df2 = df.copy()
In [610]: df2.ix[subindex, ['C', 'B']] = 0
In [611]: df2
Out[611]:
A B C D
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632
2000-01-02 -0.173215 1.212112 0.119209 -1.044236
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804
2000-01-04 -0.706771 0.000000 0.000000 0.271860
2000-01-05 0.567020 0.000000 0.000000 -1.087401
2000-01-06 0.113648 0.000000 0.000000 0.524988
2000-01-07 0.577046 0.404705 -1.715002 -1.039268
2000-01-08 -1.157892 -0.370647 -1.344312 0.844885
Indexing with an array of integers can also be done:
In [612]: df.ix[[4,3,1]]
Out[612]:
A B C D
2000-01-05 0.567020 -0.424972 0.276232 -1.087401
2000-01-04 -0.706771 0.721555 -1.039575 0.271860
2000-01-02 -0.173215 1.212112 0.119209 -1.044236
In [613]: df.ix[dates[[4,3,1]]]
Out[613]:
A B C D
2000-01-05 0.567020 -0.424972 0.276232 -1.087401
2000-01-04 -0.706771 0.721555 -1.039575 0.271860
2000-01-02 -0.173215 1.212112 0.119209 -1.044236
Slicing has standard Python semantics for integer slices:
In [614]: df.ix[1:7, :2]
Out[614]:
A B
2000-01-02 -0.173215 1.212112
2000-01-03 -2.104569 -0.861849
2000-01-04 -0.706771 0.721555
2000-01-05 0.567020 -0.424972
2000-01-06 0.113648 -0.673690
2000-01-07 0.577046 0.404705
Slicing with labels is semantically slightly different because the slice start and stop are inclusive in the label-based case:
In [615]: date1, date2 = dates[[2, 4]]
In [616]: print date1, date2
1970-01-11 232:00:00 1970-01-11 24:00:00
In [617]: df.ix[date1:date2]
Out[617]:
Empty DataFrame
Columns: array([A, B, C, D], dtype=object)
Index: <class 'pandas.tseries.index.DatetimeIndex'>
Length: 0, Freq: None, Timezone: None
In [618]: df['A'].ix[date1:date2]
Out[618]: TimeSeries([], dtype=float64)
Getting and setting rows in a DataFrame, especially by their location, is much easier:
In [619]: df2 = df[:5].copy()
In [620]: df2.ix[3]
Out[620]:
A -0.706771
B 0.721555
C -1.039575
D 0.271860
Name: 2000-01-04 00:00:00
In [621]: df2.ix[3] = np.arange(len(df2.columns))
In [622]: df2
Out[622]:
A B C D
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632
2000-01-02 -0.173215 1.212112 0.119209 -1.044236
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804
2000-01-04 0.000000 1.000000 2.000000 3.000000
2000-01-05 0.567020 -0.424972 0.276232 -1.087401
Column or row selection can be combined as you would expect with arrays of labels or even boolean vectors:
In [623]: df.ix[df['A'] > 0, 'B']
Out[623]:
2000-01-05 -0.424972
2000-01-06 -0.673690
2000-01-07 0.404705
Name: B
In [624]: df.ix[date1:date2, 'B']
Out[624]: TimeSeries([], dtype=float64)
In [625]: df.ix[date1, 'B']
Out[625]: -0.86184896334779992
Slicing with labels is closely related to the truncate method which does precisely .ix[start:stop] but returns a copy (for legacy reasons).
Returning a view versus a copy¶
The rules about when a view on the data is returned are entirely dependent on NumPy. Whenever an array of labels or a boolean vector are involved in the indexing operation, the result will be a copy. With single label / scalar indexing and slicing, e.g. df.ix[3:6] or df.ix[:, 'A'], a view will be returned.
The select method¶
Another way to extract slices from an object is with the select method of Series, DataFrame, and Panel. This method should be used only when there is no more direct way. select takes a function which operates on labels along axis and returns a boolean. For instance:
In [626]: df.select(lambda x: x == 'A', axis=1)
Out[626]:
A
2000-01-01 -0.282863
2000-01-02 -0.173215
2000-01-03 -2.104569
2000-01-04 -0.706771
2000-01-05 0.567020
2000-01-06 0.113648
2000-01-07 0.577046
2000-01-08 -1.157892
The lookup method¶
Sometimes you want to extract a set of values given a sequence of row labels and column labels, and the lookup method allows for this and returns a numpy array. For instance,
In [627]: dflookup = DataFrame(np.random.rand(20,4), columns = ['A','B','C','D'])
In [628]: dflookup.lookup(xrange(0,10,2), ['B','C','A','B','D'])
Out[628]: array([ 0.0227, 0.4199, 0.529 , 0.9674, 0.5357])
Advanced indexing with integer labels¶
Label-based indexing with integer axis labels is a thorny topic. It has been discussed heavily on mailing lists and among various members of the scientific Python community. In pandas, our general viewpoint is that labels matter more than integer locations. Therefore, with an integer axis index only label-based indexing is possible with the standard tools like .ix. The following code will generate exceptions:
s = Series(range(5))
s[-1]
df = DataFrame(np.random.randn(5, 4))
df
df.ix[-2:]
This deliberate decision was made to prevent ambiguities and subtle bugs (many users reported finding bugs when the API change was made to stop “falling back” on position-based indexing).
Setting values in mixed-type DataFrame¶
Setting values on a mixed-type DataFrame or Panel is supported when using scalar values, though setting arbitrary vectors is not yet supported:
In [629]: df2 = df[:4]
In [630]: df2['foo'] = 'bar'
In [631]: print df2
A B C D foo
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632 bar
2000-01-02 -0.173215 1.212112 0.119209 -1.044236 bar
2000-01-03 -2.104569 -0.861849 -0.494929 1.071804 bar
2000-01-04 -0.706771 0.721555 -1.039575 0.271860 bar
In [632]: df2.ix[2] = np.nan
In [633]: print df2
A B C D foo
2000-01-01 -0.282863 0.469112 -1.509059 -1.135632 bar
2000-01-02 -0.173215 1.212112 0.119209 -1.044236 bar
2000-01-03 NaN NaN NaN NaN NaN
2000-01-04 -0.706771 0.721555 -1.039575 0.271860 bar
In [634]: print df2.dtypes
A float64
B float64
C float64
D float64
foo object
Index objects¶
The pandas Index class and its subclasses can be viewed as implementing an ordered set in addition to providing the support infrastructure necessary for lookups, data alignment, and reindexing. The easiest way to create one directly is to pass a list or other sequence to Index:
In [635]: index = Index(['e', 'd', 'a', 'b'])
In [636]: index
Out[636]: Index([e, d, a, b], dtype=object)
In [637]: 'd' in index
Out[637]: True
You can also pass a name to be stored in the index:
In [638]: index = Index(['e', 'd', 'a', 'b'], name='something')
In [639]: index.name
Out[639]: 'something'
Starting with pandas 0.5, the name, if set, will be shown in the console display:
In [640]: index = Index(range(5), name='rows')
In [641]: columns = Index(['A', 'B', 'C'], name='cols')
In [642]: df = DataFrame(np.random.randn(5, 3), index=index, columns=columns)
In [643]: df
Out[643]:
cols A B C
rows
0 0.192451 0.629675 -1.425966
1 1.857704 -1.193545 0.677510
2 -0.153931 0.520091 -1.475051
3 0.722570 -0.322646 -1.601631
4 0.778033 -0.289342 0.233141
In [644]: df['A']
Out[644]:
rows
0 0.192451
1 1.857704
2 -0.153931
3 0.722570
4 0.778033
Name: A
Set operations on Index objects¶
The three main operations are union (|), intersection (&), and diff (-). These can be directly called as instance methods or used via overloaded operators:
In [645]: a = Index(['c', 'b', 'a'])
In [646]: b = Index(['c', 'e', 'd'])
In [647]: a.union(b)
Out[647]: Index([a, b, c, d, e], dtype=object)
In [648]: a | b
Out[648]: Index([a, b, c, d, e], dtype=object)
In [649]: a & b
Out[649]: Index([c], dtype=object)
In [650]: a - b
Out[650]: Index([a, b], dtype=object)
Hierarchical indexing (MultiIndex)¶
Hierarchical indexing (also referred to as “multi-level” indexing) is brand new in the pandas 0.4 release. It is very exciting as it opens the door to some quite sophisticated data analysis and manipulation, especially for working with higher dimensional data. In essence, it enables you to store and manipulate data with an arbitrary number of dimensions in lower dimensional data structures like Series (1d) and DataFrame (2d).
In this section, we will show what exactly we mean by “hierarchical” indexing and how it integrates with the all of the pandas indexing functionality described above and in prior sections. Later, when discussing group by and pivoting and reshaping data, we’ll show non-trivial applications to illustrate how it aids in structuring data for analysis.
Note
Given that hierarchical indexing is so new to the library, it is definitely “bleeding-edge” functionality but is certainly suitable for production. But, there may inevitably be some minor API changes as more use cases are explored and any weaknesses in the design / implementation are identified. pandas aims to be “eminently usable” so any feedback about new functionality like this is extremely helpful.
Creating a MultiIndex (hierarchical index) object¶
The MultiIndex object is the hierarchical analogue of the standard Index object which typically stores the axis labels in pandas objects. You can think of MultiIndex an array of tuples where each tuple is unique. A MultiIndex can be created from a list of arrays (using MultiIndex.from_arrays) or an array of tuples (using MultiIndex.from_tuples).
In [651]: arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
.....: ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
.....:
In [652]: tuples = zip(*arrays)
In [653]: tuples
Out[653]:
[('bar', 'one'),
('bar', 'two'),
('baz', 'one'),
('baz', 'two'),
('foo', 'one'),
('foo', 'two'),
('qux', 'one'),
('qux', 'two')]
In [654]: index = MultiIndex.from_tuples(tuples, names=['first', 'second'])
In [655]: s = Series(randn(8), index=index)
In [656]: s
Out[656]:
first second
bar one -0.223540
two 0.542054
baz one -0.688585
two -0.352676
foo one -0.711411
two -2.122599
qux one 1.962935
two 1.672027
As a convenience, you can pass a list of arrays directly into Series or DataFrame to construct a MultiIndex automatically:
In [657]: arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
.....: np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
.....:
In [658]: s = Series(randn(8), index=arrays)
In [659]: s
Out[659]:
bar one -0.880984
two 0.997289
baz one -1.693316
two -0.179129
foo one -1.598062
two 0.936914
qux one 0.912560
two -1.003401
In [660]: df = DataFrame(randn(8, 4), index=arrays)
In [661]: df
Out[661]:
0 1 2 3
bar one 1.632781 -0.724626 0.178219 0.310610
two -0.108002 -0.974226 -1.147708 -2.281374
baz one 0.760010 -0.742532 1.533318 2.495362
two -0.432771 -0.068954 0.043520 0.112246
foo one 0.871721 -0.816064 -0.784880 1.030659
two 0.187483 -1.933946 0.377312 0.734122
qux one 2.141616 -0.011225 0.048869 -1.360687
two -0.479010 -0.859661 -0.231595 -0.527750
All of the MultiIndex constructors accept a names argument which stores string names for the levels themselves. If no names are provided, some arbitrary ones will be assigned:
In [662]: index.names
Out[662]: ['first', 'second']
This index can back any axis of a pandas object, and the number of levels of the index is up to you:
In [663]: df = DataFrame(randn(3, 8), index=['A', 'B', 'C'], columns=index)
In [664]: df
Out[664]:
first bar baz foo qux
second one two one two one two one two
A -1.296337 0.150680 0.123836 0.571764 1.555563 -0.823761 0.535420 -1.032853
B 1.469725 1.304124 1.449735 0.203109 -1.032011 0.969818 -0.962723 1.382083
C -0.938794 0.669142 -0.433567 -0.273610 0.680433 -0.308450 -0.276099 -1.821168
In [665]: DataFrame(randn(6, 6), index=index[:6], columns=index[:6])
Out[665]:
first bar baz foo
second one two one two one two
first second
bar one -1.993606 -1.927385 -2.027924 1.624972 0.551135 3.059267
two 0.455264 -0.030740 0.935716 1.061192 -2.107852 0.199905
baz one 0.323586 -0.641630 -0.587514 0.053897 0.194889 -0.381994
two 0.318587 2.089075 -0.728293 -0.090255 -0.748199 1.318931
foo one -2.029766 0.792652 0.461007 -0.542749 -0.305384 -0.479195
two 0.095031 -0.270099 -0.707140 -0.773882 0.229453 0.304418
We’ve “sparsified” the higher levels of the indexes to make the console output a bit easier on the eyes.
It’s worth keeping in mind that there’s nothing preventing you from using tuples as atomic labels on an axis:
In [666]: Series(randn(8), index=tuples)
Out[666]:
('bar', 'one') 0.736135
('bar', 'two') -0.859631
('baz', 'one') -0.424100
('baz', 'two') -0.776114
('foo', 'one') 1.279293
('foo', 'two') 0.943798
('qux', 'one') -1.001859
('qux', 'two') 0.306546
The reason that the MultiIndex matters is that it can allow you to do grouping, selection, and reshaping operations as we will describe below and in subsequent areas of the documentation. As you will see in later sections, you can find yourself working with hierarchically-indexed data without creating a MultiIndex explicitly yourself. However, when loading data from a file, you may wish to generate your own MultiIndex when preparing the data set.
Note that how the index is displayed by be controlled using the multi_sparse option in pandas.set_printoptions:
In [667]: pd.set_printoptions(multi_sparse=False)
In [668]: df
Out[668]:
first bar bar baz baz foo foo qux qux
second one two one two one two one two
A -1.296337 0.150680 0.123836 0.571764 1.555563 -0.823761 0.535420 -1.032853
B 1.469725 1.304124 1.449735 0.203109 -1.032011 0.969818 -0.962723 1.382083
C -0.938794 0.669142 -0.433567 -0.273610 0.680433 -0.308450 -0.276099 -1.821168
In [669]: pd.set_printoptions(multi_sparse=True)
Reconstructing the level labels¶
The method get_level_values will return a vector of the labels for each location at a particular level:
In [670]: index.get_level_values(0)
Out[670]: array([bar, bar, baz, baz, foo, foo, qux, qux], dtype=object)
In [671]: index.get_level_values('second')
Out[671]: array([one, two, one, two, one, two, one, two], dtype=object)
Basic indexing on axis with MultiIndex¶
One of the important features of hierarchical indexing is that you can select data by a “partial” label identifying a subgroup in the data. Partial selection “drops” levels of the hierarchical index in the result in a completely analogous way to selecting a column in a regular DataFrame:
In [672]: df['bar']
Out[672]:
second one two
A -1.296337 0.150680
B 1.469725 1.304124
C -0.938794 0.669142
In [673]: df['bar', 'one']
Out[673]:
A -1.296337
B 1.469725
C -0.938794
Name: ('bar', 'one')
In [674]: df['bar']['one']
Out[674]:
A -1.296337
B 1.469725
C -0.938794
Name: one
In [675]: s['qux']
Out[675]:
one 0.912560
two -1.003401
Data alignment and using reindex¶
Operations between differently-indexed objects having MultiIndex on the axes will work as you expect; data alignment will work the same as an Index of tuples:
In [676]: s + s[:-2]
Out[676]:
bar one -1.761968
two 1.994577
baz one -3.386631
two -0.358257
foo one -3.196125
two 1.873828
qux one NaN
two NaN
In [677]: s + s[::2]
Out[677]:
bar one -1.761968
two NaN
baz one -3.386631
two NaN
foo one -3.196125
two NaN
qux one 1.825119
two NaN
reindex can be called with another MultiIndex or even a list or array of tuples:
In [678]: s.reindex(index[:3])
Out[678]:
first second
bar one -0.880984
two 0.997289
baz one -1.693316
In [679]: s.reindex([('foo', 'two'), ('bar', 'one'), ('qux', 'one'), ('baz', 'one')])
Out[679]:
foo two 0.936914
bar one -0.880984
qux one 0.912560
baz one -1.693316
Advanced indexing with hierarchical index¶
Syntactically integrating MultiIndex in advanced indexing with .ix is a bit challenging, but we’ve made every effort to do so. for example the following works as you would expect:
In [680]: df = df.T
In [681]: df
Out[681]:
A B C
first second
bar one -1.296337 1.469725 -0.938794
two 0.150680 1.304124 0.669142
baz one 0.123836 1.449735 -0.433567
two 0.571764 0.203109 -0.273610
foo one 1.555563 -1.032011 0.680433
two -0.823761 0.969818 -0.308450
qux one 0.535420 -0.962723 -0.276099
two -1.032853 1.382083 -1.821168
In [682]: df.ix['bar']
Out[682]:
A B C
second
one -1.296337 1.469725 -0.938794
two 0.150680 1.304124 0.669142
In [683]: df.ix['bar', 'two']
Out[683]:
A 0.150680
B 1.304124
C 0.669142
Name: ('bar', 'two')
“Partial” slicing also works quite nicely:
In [684]: df.ix['baz':'foo']
Out[684]:
A B C
first second
baz one 0.123836 1.449735 -0.433567
two 0.571764 0.203109 -0.273610
foo one 1.555563 -1.032011 0.680433
two -0.823761 0.969818 -0.308450
In [685]: df.ix[('baz', 'two'):('qux', 'one')]
Out[685]:
A B C
first second
baz two 0.571764 0.203109 -0.273610
foo one 1.555563 -1.032011 0.680433
two -0.823761 0.969818 -0.308450
qux one 0.535420 -0.962723 -0.276099
In [686]: df.ix[('baz', 'two'):'foo']
Out[686]:
A B C
first second
baz two 0.571764 0.203109 -0.273610
foo one 1.555563 -1.032011 0.680433
two -0.823761 0.969818 -0.308450
Passing a list of labels or tuples works similar to reindexing:
In [687]: df.ix[[('bar', 'two'), ('qux', 'one')]]
Out[687]:
A B C
first second
bar two 0.15068 1.304124 0.669142
qux one 0.53542 -0.962723 -0.276099
The following does not work, and it’s not clear if it should or not:
>>> df.ix[['bar', 'qux']]
The code for implementing .ix makes every attempt to “do the right thing” but as you use it you may uncover corner cases or unintuitive behavior. If you do find something like this, do not hesitate to report the issue or ask on the mailing list.
Cross-section with hierarchical index¶
The xs method of DataFrame additionally takes a level argument to make selecting data at a particular level of a MultiIndex easier.
In [688]: df.xs('one', level='second')
Out[688]:
A B C
first
bar -1.296337 1.469725 -0.938794
baz 0.123836 1.449735 -0.433567
foo 1.555563 -1.032011 0.680433
qux 0.535420 -0.962723 -0.276099
Advanced reindexing and alignment with hierarchical index¶
The parameter level has been added to the reindex and align methods of pandas objects. This is useful to broadcast values across a level. For instance:
In [689]: midx = MultiIndex(levels=[['zero', 'one'], ['x','y']],
.....: labels=[[1,1,0,0],[1,0,1,0]])
.....:
In [690]: df = DataFrame(randn(4,2), index=midx)
In [691]: print df
0 1
one y 0.307453 -0.906534
x -1.505397 1.392009
zero y -0.027793 -0.631023
x -0.662357 2.725042
In [692]: df2 = df.mean(level=0)
In [693]: print df2
0 1
zero -0.345075 1.047010
one -0.598972 0.242737
In [694]: print df2.reindex(df.index, level=0)
0 1
one y -0.598972 0.242737
x -0.598972 0.242737
zero y -0.345075 1.047010
x -0.345075 1.047010
In [695]: df_aligned, df2_aligned = df.align(df2, level=0)
In [696]: print df_aligned
0 1
one y 0.307453 -0.906534
x -1.505397 1.392009
zero y -0.027793 -0.631023
x -0.662357 2.725042
In [697]: print df2_aligned
0 1
one y -0.598972 0.242737
x -0.598972 0.242737
zero y -0.345075 1.047010
x -0.345075 1.047010
The need for sortedness¶
Caveat emptor: the present implementation of MultiIndex requires that the labels be sorted for some of the slicing / indexing routines to work correctly. You can think about breaking the axis into unique groups, where at the hierarchical level of interest, each distinct group shares a label, but no two have the same label. However, the MultiIndex does not enforce this: you are responsible for ensuring that things are properly sorted. There is an important new method sortlevel to sort an axis within a MultiIndex so that its labels are grouped and sorted by the original ordering of the associated factor at that level. Note that this does not necessarily mean the labels will be sorted lexicographically!
In [698]: import random; random.shuffle(tuples)
In [699]: s = Series(randn(8), index=MultiIndex.from_tuples(tuples))
In [700]: s
Out[700]:
qux two -1.847240
baz two -0.529247
bar two 0.614656
foo two -1.590742
baz one -0.156479
qux one -1.696377
foo one 0.819712
bar one -2.107728
In [701]: s.sortlevel(0)
Out[701]:
bar one -2.107728
two 0.614656
baz one -0.156479
two -0.529247
foo one 0.819712
two -1.590742
qux one -1.696377
two -1.847240
In [702]: s.sortlevel(1)
Out[702]:
bar one -2.107728
baz one -0.156479
foo one 0.819712
qux one -1.696377
bar two 0.614656
baz two -0.529247
foo two -1.590742
qux two -1.847240
Note, you may also pass a level name to sortlevel if the MultiIndex levels are named.
In [703]: s.index.names = ['L1', 'L2']
In [704]: s.sortlevel(level='L1')
Out[704]:
L1 L2
bar one -2.107728
two 0.614656
baz one -0.156479
two -0.529247
foo one 0.819712
two -1.590742
qux one -1.696377
two -1.847240
In [705]: s.sortlevel(level='L2')
Out[705]:
L1 L2
bar one -2.107728
baz one -0.156479
foo one 0.819712
qux one -1.696377
bar two 0.614656
baz two -0.529247
foo two -1.590742
qux two -1.847240
Some indexing will work even if the data are not sorted, but will be rather inefficient and will also return a copy of the data rather than a view:
In [706]: s['qux']
Out[706]:
L2
two -1.847240
one -1.696377
In [707]: s.sortlevel(1)['qux']
Out[707]:
L2
one -1.696377
two -1.847240
On higher dimensional objects, you can sort any of the other axes by level if they have a MultiIndex:
In [708]: df.T.sortlevel(1, axis=1)
Out[708]:
zero one zero one
x x y y
0 -0.662357 -1.505397 -0.027793 0.307453
1 2.725042 1.392009 -0.631023 -0.906534
The MultiIndex object has code to explicity check the sort depth. Thus, if you try to index at a depth at which the index is not sorted, it will raise an exception. Here is a concrete example to illustrate this:
In [709]: tuples = [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
In [710]: idx = MultiIndex.from_tuples(tuples)
In [711]: idx.lexsort_depth
Out[711]: 2
In [712]: reordered = idx[[1, 0, 3, 2]]
In [713]: reordered.lexsort_depth
Out[713]: 1
In [714]: s = Series(randn(4), index=reordered)
In [715]: s.ix['a':'a']
Out[715]:
a b -0.488326
a 0.851918
However:
>>> s.ix[('a', 'b'):('b', 'a')]
Exception: MultiIndex lexsort depth 1, key was length 2
Swapping levels with swaplevel¶
The swaplevel function can switch the order of two levels:
In [716]: df[:5]
Out[716]:
0 1
one y 0.307453 -0.906534
x -1.505397 1.392009
zero y -0.027793 -0.631023
x -0.662357 2.725042
In [717]: df[:5].swaplevel(0, 1, axis=0)
Out[717]:
0 1
y one 0.307453 -0.906534
x one -1.505397 1.392009
y zero -0.027793 -0.631023
x zero -0.662357 2.725042
Reordering levels with reorder_levels¶
The reorder_levels function generalizes the swaplevel function, allowing you to permute the hierarchical index levels in one step:
In [718]: df[:5].reorder_levels([1,0], axis=0)
Out[718]:
0 1
y one 0.307453 -0.906534
x one -1.505397 1.392009
y zero -0.027793 -0.631023
x zero -0.662357 2.725042
Some gory internal details¶
Internally, the MultiIndex consists of a few things: the levels, the integer labels, and the level names:
In [719]: index
Out[719]:
MultiIndex
[('bar', 'one') ('bar', 'two') ('baz', 'one') ('baz', 'two')
('foo', 'one') ('foo', 'two') ('qux', 'one') ('qux', 'two')]
In [720]: index.levels
Out[720]: [Index([bar, baz, foo, qux], dtype=object), Index([one, two], dtype=object)]
In [721]: index.labels
Out[721]: [array([0, 0, 1, 1, 2, 2, 3, 3]), array([0, 1, 0, 1, 0, 1, 0, 1])]
In [722]: index.names
Out[722]: ['first', 'second']
You can probably guess that the labels determine which unique element is identified with that location at each layer of the index. It’s important to note that sortedness is determined solely from the integer labels and does not check (or care) whether the levels themselves are sorted. Fortunately, the constructors from_tuples and from_arrays ensure that this is true, but if you compute the levels and labels yourself, please be careful.
Adding an index to an existing DataFrame¶
Occasionally you will load or create a data set into a DataFrame and want to add an index after you’ve already done so. There are a couple of different ways.
Add an index using DataFrame columns¶
DataFrame has a set_index method which takes a column name (for a regular Index) or a list of column names (for a MultiIndex), to create a new, indexed DataFrame:
In [723]: data
Out[723]:
a b c d
0 bar one z 1
1 bar two y 2
2 foo one x 3
3 foo two w 4
In [724]: indexed1 = data.set_index('c')
In [725]: indexed1
Out[725]:
a b d
c
z bar one 1
y bar two 2
x foo one 3
w foo two 4
In [726]: indexed2 = data.set_index(['a', 'b'])
In [727]: indexed2
Out[727]:
c d
a b
bar one z 1
two y 2
foo one x 3
two w 4
The append keyword option allow you to keep the existing index and append the given columns to a MultiIndex:
In [728]: frame = data.set_index('c', drop=False)
In [729]: frame = frame.set_index(['a', 'b'], append=True)
In [730]: frame
Out[730]:
c d
c a b
z bar one z 1
y bar two y 2
x foo one x 3
w foo two w 4
Other options in set_index allow you not drop the index columns or to add the index in-place (without creating a new object):
In [731]: data.set_index('c', drop=False)
Out[731]:
a b c d
c
z bar one z 1
y bar two y 2
x foo one x 3
w foo two w 4
In [732]: df = data.set_index(['a', 'b'], inplace=True)
In [733]: data
Out[733]:
c d
a b
bar one z 1
two y 2
foo one x 3
two w 4
Remove / reset the index, reset_index¶
As a convenience, there is a new function on DataFrame called reset_index which transfers the index values into the DataFrame’s columns and sets a simple integer index. This is the inverse operation to set_index
In [734]: df
Out[734]:
c d
a b
bar one z 1
two y 2
foo one x 3
two w 4
In [735]: df.reset_index()
Out[735]:
a b c d
0 bar one z 1
1 bar two y 2
2 foo one x 3
3 foo two w 4
The output is more similar to a SQL table or a record array. The names for the columns derived from the index are the ones stored in the names attribute.
You can use the level keyword to remove only a portion of the index:
In [736]: frame
Out[736]:
c d
c a b
z bar one z 1
y bar two y 2
x foo one x 3
w foo two w 4
In [737]: frame.reset_index(level=1)
Out[737]:
a c d
c b
z one bar z 1
y two bar y 2
x one foo x 3
w two foo w 4
reset_index takes an optional parameter drop which if true simply discards the index, instead of putting index values in the DataFrame’s columns.
Note
The reset_index method used to be called delevel which is now deprecated.
Adding an ad hoc index¶
If you create an index yourself, you can just assign it to the index field:
df.index = index
Indexing internal details¶
Note
The following is largely relevant for those actually working on the pandas codebase. And the source code is still the best place to look at the specifics of how things are implemented.
In pandas there are a few objects implemented which can serve as valid containers for the axis labels:
- Index: the generic “ordered set” object, an ndarray of object dtype assuming nothing about its contents. The labels must be hashable (and likely immutable) and unique. Populates a dict of label to location in Cython to do lookups.
- Int64Index: a version of Index highly optimized for 64-bit integer data, such as time stamps
- MultiIndex: the standard hierarchical index object
- date_range: fixed frequency date range generated from a time rule or DateOffset. An ndarray of Python datetime objects
The motivation for having an Index class in the first place was to enable different implementations of indexing. This means that it’s possible for you, the user, to implement a custom Index subclass that may be better suited to a particular application than the ones provided in pandas. For example, we plan to add a more efficient datetime index which leverages the new numpy.datetime64 dtype in the relatively near future.
From an internal implementation point of view, the relevant methods that an Index must define are one or more of the following (depending on how incompatible the new object internals are with the Index functions):
- get_loc: returns an “indexer” (an integer, or in some cases a slice object) for a label
- slice_locs: returns the “range” to slice between two labels
- get_indexer: Computes the indexing vector for reindexing / data alignment purposes. See the source / docstrings for more on this
- reindex: Does any pre-conversion of the input index then calls get_indexer
- union, intersection: computes the union or intersection of two Index objects
- insert: Inserts a new label into an Index, yielding a new object
- delete: Delete a label, yielding a new object
- drop: Deletes a set of labels
- take: Analogous to ndarray.take