Select rows in pandas MultiIndex DataFrame
多年来,
一个重要的操作是过滤。过滤是一种常见的要求,但用例是多种多样的。因此,某些方法和功能将比其他用例更适用于某些用例。
总之,本文的目的是触及一些常见的过滤问题和用例,演示解决这些问题的各种不同方法,并讨论它们的适用性。本文试图解决的一些高级问题是
- 基于单个值/标签切片
- 基于来自一个或多个级别的多个标签进行切片
- 过滤布尔条件和表达式
- 哪种方法适用于什么情况
这些问题已分解为6个具体问题,如下所列。为简单起见,以下设置中的示例DataFrame仅具有两个级别,并且没有重复的索引键。提出问题的大多数解决方案可以推广到N级。
本文不会介绍如何创建MultiIndexes,如何对它们执行赋值操作,或任何与性能相关的讨论(这些是另一个时间的单独主题)。
问题
Question 1-6 will be asked in context to the setup below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 mux = pd.MultiIndex.from_arrays([
list('aaaabbbbbccddddd'),
list('tuvwtuvwtuvwtuvw')
], names=['one', 'two'])
df = pd.DataFrame({'col': np.arange(len(mux))}, mux)
col
one two
a t 0
u 1
v 2
w 3
b t 4
u 5
v 6
w 7
t 8
c u 9
v 10
d w 11
t 12
u 13
v 14
w 15
问题1:选择单个项目
如何在"一"级中选择"a"的行?
1 2 3 4 5 6 | col one two a t 0 u 1 v 2 w 3 |
另外,我怎样才能在输出中删除"1"级?
1 2 3 4 5 6 | col two t 0 u 1 v 2 w 3 |
问题1b
如何在"2"级别上切换值为"t"的所有行?
1 2 3 4 5 6 | col one two a t 0 b t 4 t 8 d t 12 |
问题2:在一个级别中选择多个值
如何在"一"级中选择与"b"和"d"项对应的行?
1 2 3 4 5 6 7 8 9 10 11 12 | col one two b t 4 u 5 v 6 w 7 t 8 d w 11 t 12 u 13 v 14 w 15 |
问题2b
如何在"2"级中获得与"t"和"w"对应的所有值?
1 2 3 4 5 6 7 8 9 10 | col one two a t 0 w 3 b t 4 w 7 t 8 d w 11 t 12 w 15 |
问题3:切片单个横截面
如何从
1 2 3 | col one two c u 9 |
问题4:切片多个横截面
如何选择与
1 2 3 4 | col one two c u 9 a w 3 |
问题5:每个级别切一个项目
如何检索"2"级中"a"或"t"级别中"a"对应的所有行?
1 2 3 4 5 6 7 8 9 | col one two a t 0 u 1 v 2 w 3 b t 4 t 8 d t 12 |
问题6:任意切片
如何切割特定的横截面?对于"a"和"b",我想选择具有子级别"u"和"v"的所有行,而对于"d",我想选择具有子级别"w"的行。
1 2 3 4 5 6 7 8 | col one two a u 1 v 2 b u 5 v 6 d w 11 w 15 |
Question 7 will use a unique setup consisting of a numeric level:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 np.random.seed(0)
mux2 = pd.MultiIndex.from_arrays([
list('aaaabbbbbccddddd'),
np.random.choice(10, size=16)
], names=['one', 'two'])
df2 = pd.DataFrame({'col': np.arange(len(mux2))}, mux2)
col
one two
a 5 0
0 1
3 2
3 3
b 7 4
9 5
3 6
5 7
2 8
c 4 9
7 10
d 6 11
8 12
8 13
1 14
6 15
问题7:基于不等式的数值级别过滤
如何获取级别"2"中的值大于5的所有行?
1 2 3 4 5 6 7 8 9 | col one two b 7 4 9 5 c 7 10 d 6 11 8 12 8 13 6 15 |
MultiIndex / Advanced Indexing
Note
This post will be structured in the following manner:Ok.
The questions put forth in the OP will be addressed, one by one For each question, one or more methods applicable to solving this problem and getting the expected result will be demonstrated. Notes (much like this one) will be included for readers interested in learning about additional functionality, implementation details,
and other info cursory to the topic at hand. These notes have been
compiled through scouring the docs and uncovering various obscure
features, and from my own (admittedly limited) experience.Ok.
All code samples have created and tested on pandas v0.23.4, python3.7. If something is not clear, or factually incorrect, or if you did not
find a solution applicable to your use case, please feel free to
suggest an edit, request clarification in the comments, or open a new
question, ....as applicable.Ok.
以下是我们将经常重访的一些常见习语(以下简称四种习语)的介绍
使用
考虑四种习语的各种切片和过滤问题以更好地理解可应用于给定情况的内容将是有益的。非常重要的是要理解并非所有习语在每种情况下都能同样有效(如果有的话)。如果一个成语没有列为下面问题的潜在解决方案,那就意味着成语不能有效地应用于该问题。
Question 1
How do I select rows having"a" in level"one"?
Ok.
1
2
3
4
5
6 col
one two
a t 0
u 1
v 2
w 3
您可以使用
1 | df.loc[['a']] |
在这一点上,如果你得到
1 | TypeError: Expected tuple, got str |
这意味着你正在使用旧版本的熊猫。考虑升级!否则,请使用
或者,您可以在此处使用
1 2 | df.xs('a', level=0, axis=0, drop_level=False) # df.xs('a', drop_level=False) |
这里,需要
这里的另一个选择是使用
1 | df.query("one == 'a'") |
如果索引没有名称,则需要将查询字符串更改为
最后,使用
1 2 3 | df[df.index.get_level_values('one') == 'a'] # If your levels are unnamed, or if you need to select by position (not label), # df[df.index.get_level_values(0) == 'a'] |
Additionally, how would I be able to drop level"one" in the output?
Ok.
1
2
3
4
5
6 col
two
t 0
u 1
v 2
w 3
这可以使用其中任何一个轻松完成
1 | df.loc['a'] # Notice the single string argument instead the list. |
要么,
1 2 | df.xs('a', level=0, axis=0, drop_level=True) # df.xs('a') |
请注意,我们可以省略
Note
You may notice that a filtered DataFrame may still have all the levels, even if they do not show when printing the DataFrame out. For example,Ok.
1
2
3
4
5
6
7
8
9
10
11
12
13 v = df.loc[['a']]
print(v)
col
one two
a t 0
u 1
v 2
w 3
print(v.index)
MultiIndex(levels=[['a', 'b', 'c', 'd'], ['t', 'u', 'v', 'w']],
labels=[[0, 0, 0, 0], [0, 1, 2, 3]],
names=['one', 'two'])You can get rid of these levels using
MultiIndex.remove_unused_levels :Ok.
1
2
3
4
5
6 v.index = v.index.remove_unused_levels()
print(v.index)
MultiIndex(levels=[['a'], ['t', 'u', 'v', 'w']],
labels=[[0, 0, 0, 0], [0, 1, 2, 3]],
names=['one', 'two'])
Question 1b
How do I slice all rows with value"t" on level"two"?
Ok.
1
2
3
4
5
6 col
one two
a t 0
b t 4
t 8
d t 12
直觉上,你会想要涉及
1 | df.loc[(slice(None), 't'), :] |
它只是工作!?但它很笨重。我们可以在这里使用
1 2 | idx = pd.IndexSlice df.loc[idx[:, 't'], :] |
这更加清洁。
Note
Why is the trailing slice: across the columns required? This is because,loc can be used to select and slice along both axes (axis=0 or
axis=1 ). Without explicitly making it clear which axis the slicing
is to be done on, the operation becomes ambiguous. See the big red box in the documentation on slicing.Ok.
If you want to remove any shade of ambiguity,
loc accepts anaxis
parameter:Ok.
1 df.loc(axis=0)[pd.IndexSlice[:, 't']]Without the
axis parameter (i.e., just by doingdf.loc[pd.IndexSlice[:, 't']] ), slicing is assumed to be on the columns,
and aKeyError will be raised in this circumstance.Ok.
This is documented in slicers. For the purpose of this post, however, we will explicitly specify all axes.
Ok.
使用
1 | df.xs('t', axis=0, level=1, drop_level=False) |
使用
1 2 3 | df.query("two == 't'") # Or, if the first level has no name, # df.query("ilevel_1 == 't'") |
最后,使用
1 2 3 | df[df.index.get_level_values('two') == 't'] # Or, to perform selection by position/integer, # df[df.index.get_level_values(1) == 't'] |
一切都达到了同样的效果。
Question 2
How can I select rows corresponding to items"b" and"d" in level"one"?
Ok.
1
2
3
4
5
6
7
8
9
10
11
12 col
one two
b t 4
u 5
v 6
w 7
t 8
d w 11
t 12
u 13
v 14
w 15
使用loc,通过指定列表以类似的方式完成。
1 | df.loc[['b', 'd']] |
要解决上面选择"b"和"d"的问题,你也可以使用
1 2 3 4 5 | items = ['b', 'd'] df.query("one in @items") # df.query("one == @items", parser='pandas') # df.query("one in ['b', 'd']") # df.query("one == ['b', 'd']", parser='pandas') |
Note
Yes, the default parser is'pandas' , but it is important to highlight this syntax isn't conventionally python. The
Pandas parser generates a slightly different parse tree from the
expression. This is done to make some operations more intuitive to
specify. For more information, please read my post on
Dynamic Expression Evaluation in pandas using pd.eval().Ok.
并且,
1 | df[df.index.get_level_values("one").isin(['b', 'd'])] |
Question 2b
How would I get all values corresponding to"t" and"w" in level"two"?
Ok.
1
2
3
4
5
6
7
8
9
10 col
one two
a t 0
w 3
b t 4
w 7
t 8
d w 11
t 12
w 15
使用
1 | df.loc[pd.IndexSlice[:, ['t', 'w']], :] |
使用
1 2 3 4 5 | items = ['t', 'w'] df.query("two in @items") # df.query("two == @items", parser='pandas') # df.query("two in ['t', 'w']") # df.query("two == ['t', 'w']", parser='pandas') |
使用
1 | df[df.index.get_level_values('two').isin(['t', 'w'])] |
Question 3
How do I retrieve a cross section, i.e., a single row having a specific values
for the index fromdf ? Specifically, how do I retrieve the cross
section of('c', 'u') , given byOk.
1
2
3 col
one two
c u 9
通过指定键元组使用
1 | df.loc[('c', 'u'), :] |
要么,
1 | df.loc[pd.IndexSlice[('c', 'u')]] |
Note
At this point, you may run into aPerformanceWarning that looks like this:Ok.
1 PerformanceWarning: indexing past lexsort depth may impact performance.This just means that your index is not sorted. pandas depends on the index being sorted (in this case, lexicographically, since we are dealing with string values) for optimal search and retrieval. A quick fix would be to sort your
DataFrame in advance usingDataFrame.sort_index . This is especially desirable from a performance standpoint if you plan on doing
multiple such queries in tandem:Ok.
1
2 df_sort = df.sort_index()
df_sort.loc[('c', 'u')]You can also use
MultiIndex.is_lexsorted() to check whether the index
is sorted or not. This function returnsTrue orFalse accordingly.
You can call this function to determine whether an additional sorting
step is required or not.Ok.
使用
1 | df.xs(('c', 'u')) |
随着
1 | df.query("one == 'c' and two == 'u'") |
你现在可以看到,这将是相对难以概括的。但对于这个特殊问题仍然可以。
访问跨越多个级别,仍然可以使用
1 2 3 | m1 = (df.index.get_level_values('one') == 'c') m2 = (df.index.get_level_values('two') == 'u') df[m1 & m2] |
Question 4
How do I select the two rows corresponding to
('c', 'u') , and('a', 'w') ?Ok.
1
2
3
4 col
one two
c u 9
a w 3
使用
1 2 | df.loc[[('c', 'u'), ('a', 'w')]] # df.loc[pd.IndexSlice[[('c', 'u'), ('a', 'w')]]] |
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | cses = [('c', 'u'), ('a', 'w')] levels = ['one', 'two'] # This is a useful check to make in advance. assert all(len(levels) == len(cs) for cs in cses) query = '(' + ') or ('.join([ ' and '.join([f"({l} == {repr(c)})" for l, c in zip(levels, cs)]) for cs in cses ]) + ')' print(query) # ((one == 'c') and (two == 'u')) or ((one == 'a') and (two == 'w')) df.query(query) |
100%不推荐!但这是可能的。
Question 5
How can I retrieve all rows corresponding to"a" in level"one" or
"t" in level"two"?Ok.
1
2
3
4
5
6
7
8
9 col
one two
a t 0
u 1
v 2
w 3
b t 4
t 8
d t 12
这实际上很难用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | pd.concat([ df.loc[['a'],:], df.loc[pd.IndexSlice[:, 't'],:] ]) col one two a t 0 u 1 v 2 w 3 t 0 # Does this look right to you? No, it isn't! b t 4 t 8 d t 12 |
但是你会注意到其中一行是重复的。这是因为该行满足两个切片条件,因此出现了两次。你需要这样做
1 2 3 4 | v = pd.concat([ df.loc[['a'],:], df.loc[pd.IndexSlice[:, 't'],:] ]) v[~v.index.duplicated()] |
但是,如果您的DataFrame本身包含重复索引(您想要),那么这将不会保留它们。使用时要格外小心。
使用
1 | df.query("one == 'a' or two == 't'") |
使用
1 2 3 | m1 = (df.index.get_level_values('one') == 'c') m2 = (df.index.get_level_values('two') == 'u') df[m1 | m2] |
Question 6
How can I slice specific cross sections? For"a" and"b", I would like to select all rows with sub-levels"u" and"v", and
for"d", I would like to select rows with sub-level"w".Ok.
1
2
3
4
5
6
7
8 col
one two
a u 1
v 2
b u 5
v 6
d w 11
w 15
这是我添加的特殊情况,以帮助理解四种习语的适用性 - 这是一种情况,其中没有一种能够有效地工作,因为切片是非常具体的,并且不遵循任何真实的模式。
通常,像这样的切片问题需要显式地将键列表传递给
1 2 | keys = [('a', 'u'), ('a', 'v'), ('b', 'u'), ('b', 'v'), ('d', 'w')] df.loc[keys, :] |
如果你想保存一些打字,你会发现有一个模式可以切换"a","b"及其子级别,所以我们可以将切片任务分成两部分并且
1 2 3 4 | pd.concat([ df.loc[(('a', 'b'), ('u', 'v')), :], df.loc[('d', 'w'), :] ], axis=0) |
切片"a"和"b"的规范稍微更清晰
Question 7
How do I get all rows where values in level"two" are greater than 5?
Ok.
1
2
3
4
5
6
7
8
9 col
one two
b 7 4
9 5
c 7 10
d 6 11
8 12
8 13
6 15
这可以使用
1 | df2.query("two > 5") |
并且
1 | df2[df2.index.get_level_values('two') > 5] |
Note
Similar to this example, we can filter based on any arbitrary condition using these constructs. In general, it is useful to remember thatloc andxs are specifically for label-based indexing, whilequery and
get_level_values are helpful for building general conditional masks
for filtering.Ok.
Bonus Question
What if I need to slice a
MultiIndex column?Ok.
实际上,这里的大多数解决方案也适用于列,只有很小的变化。考虑:
1 2 3 4 5 6 7 8 9 10 11 12 13 | np.random.seed(0) mux3 = pd.MultiIndex.from_product([ list('ABCD'), list('efgh') ], names=['one','two']) df3 = pd.DataFrame(np.random.choice(10, (3, len(mux))), columns=mux3) print(df3) one A B C D two e f g h e f g h e f g h e f g h 0 5 0 3 3 7 9 3 5 2 4 7 6 8 8 1 6 1 7 7 8 1 5 9 8 9 4 3 0 3 5 0 2 3 2 8 1 3 3 3 7 0 1 9 9 0 4 7 3 2 7 |
以下是您需要对四种习语进行的更改,以使它们与列一起使用。
要使用
1 | df3.loc[:, ....] # Notice how we slice across the index with `:`. |
要么,
1 | df3.loc[:, pd.IndexSlice[...]] |
要根据需要使用
您可以使用
1 | df.loc[:, {condition}] |
其中
要使用
1 | df3.T.query(...).T |
不推荐使用其他3个选项之一。
好。