在给定级别和列值下按特定索引过滤熊猫MultiIndex

时间:2018-09-18 15:09:15

标签: python pandas multi-index

给出以下数据框:

import pandas as pd
import numpy as np

indices = [['A', 'B', 'C'], ['a', 'b', 'c', 'd'], ['1', '2', '3']]

index = pd.MultiIndex.from_product(indices, names=['first', 'second', 'third'])

df = pd.DataFrame(np.random.randint(10, size=(36, 4)), index=index, columns=['Val1','Val2',' Val3', 'Val4'])

例如,哪个产量

                    Val1  Val2  Val3  Val4
first second third                        
A     a      1         1     7     2     1
             2         0     0     8     6
             3         3     2     0     5
      b      1         3     8     8     8
             2         3     1     0     5
             3         7     2     8     5
      c      1         9     9     5     3
             2         2     5     5     8
             3         7     5     1     5
      d      1         2     7     8     6
             2         9     0     0     2
             3         9     4     1     4
B     a      1         1     2     3     3
             2         3     2     3     1
             3         1     3     2     2
      b      1         4     4     3     1
             2         9     4     8     2
             3         6     7     8     8
      c      1         6     6     3     2
             2         2     6     5     6
             3         6     4     2     7
      d      1         1     1     1     5
             2         6     4     8     1
             3         3     4     3     1
C     a      1         0     3     4     0
             2         5     0     1     4
             3         1     1     5     7
      b      1         2     6     1     7
             2         2     6     4     3
             3         0     5     6     6
      c      1         0     2     3     7
             2         7     1     1     1
             3         2     6     2     0
      d      1         6     2     2     1
             2         9     3     1     9
             3         7     5     6     1

如何通过任何索引级别和特定的列值来过滤此数据框?

编辑

例如,如果我想保留所有更高级别的索引(即level=0level=1),如果{{1}的相应third索引(level=2) }的1列值大于Val 2。因此,如果5索引中的索引1的{​​{1}}值不大于third,则对应于该索引的Val2级别索引为从数据框中删除。

我试图解决问题,或者至少传达了我的意图(因为这会产生错误):

5

这给了我以下错误:

second

在此示例中,我的预期输出如下:

df[df.loc[pd.IndexSlice[:, :, '1'], 'Val2'] > 5]

好奇是否可以通过pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match) 实现此功能,或者是否缺少在 Val1 Val2 Val3 Val4 first second third A a 1 1 7 2 1 2 0 0 8 6 3 3 2 0 5 b 1 3 8 8 8 2 3 1 0 5 3 7 2 8 5 c 1 9 9 5 3 2 2 5 5 8 3 7 5 1 5 d 1 2 7 8 6 2 9 0 0 2 3 9 4 1 4 B c 1 6 6 3 2 2 2 6 5 6 3 6 4 2 7 C b 1 2 6 1 7 2 2 6 4 3 3 0 5 6 6 上执行此过滤的简单方法?预先谢谢你。

0 个答案:

没有答案