在第一级和第二级过滤具有多列索引的数据框
Filter dataframe with multicolumn index in first & second levels
我有一个包含两列索引的数据框。
A B
one two three four
ID
A 0.895717 -1.206412 1.431256 -1.170299
B 0.410835 0.132003 -0.076467 1.130127
C -1.413681 1.024180 0.875906 0.974466
我想按照下面提到的第一级和第二级过滤它:
- 我只想说第一层
df[A]
A
one two
ID
A 0.895717 -1.206412
B 0.410835 0.132003
C -1.413681 1.024180
- 我想像这样提及二级栏目:
df[A[二],B[三,四]]
A B
ID two three four
A -1.206412 1.431256 -1.170299
B 0.132003 -0.076467 1.130127
C 1.024180 0.875906 0.974466
请帮忙!
第一选择:
df[['A']]
A
one two
ID
A 0.895717 -1.206412
B 0.410835 0.132003
C -1.413681 1.024180
第二个:
df[[('A', 'one'), ('B', 'three'), ('B', 'four')]]
A B
one three four
ID
A 0.895717 1.431256 -1.170299
B 0.410835 -0.076467 1.130127
C -1.413681 0.875906 0.974466
如果您确实有很多组合并且想要压缩选择器,您可以这样做:
l = [['A', 'one'], ['B', ['three', 'four']]]
idx = [(a,b) for A,B in l
for a in (A if isinstance(A, list) else [A])
for b in (B if isinstance(B, list) else [B])
]
df[idx]
我有一个包含两列索引的数据框。
A B
one two three four
ID
A 0.895717 -1.206412 1.431256 -1.170299
B 0.410835 0.132003 -0.076467 1.130127
C -1.413681 1.024180 0.875906 0.974466
我想按照下面提到的第一级和第二级过滤它:
- 我只想说第一层
df[A]
A
one two
ID
A 0.895717 -1.206412
B 0.410835 0.132003
C -1.413681 1.024180
- 我想像这样提及二级栏目:
df[A[二],B[三,四]]
A B
ID two three four
A -1.206412 1.431256 -1.170299
B 0.132003 -0.076467 1.130127
C 1.024180 0.875906 0.974466
请帮忙!
第一选择:
df[['A']]
A
one two
ID
A 0.895717 -1.206412
B 0.410835 0.132003
C -1.413681 1.024180
第二个:
df[[('A', 'one'), ('B', 'three'), ('B', 'four')]]
A B
one three four
ID
A 0.895717 1.431256 -1.170299
B 0.410835 -0.076467 1.130127
C -1.413681 0.875906 0.974466
如果您确实有很多组合并且想要压缩选择器,您可以这样做:
l = [['A', 'one'], ['B', ['three', 'four']]]
idx = [(a,b) for A,B in l
for a in (A if isinstance(A, list) else [A])
for b in (B if isinstance(B, list) else [B])
]
df[idx]