我有一个MultiIndex的DataFrame,如下所示:
In [5]: df
Out[5]:
a b
lvl0 lvl1 lvl2
A0 B0 C0 0 1
C1 2 3
C2 4 5
C3 6 7
B1 C0 8 9
C1 10 11
C2 12 13
C3 14 15
A1 B0 C0 16 47
C1 18 49
C2 20 41
C3 22 43
B1 C0 24 25
C1 26 27
C2 28 29
C3 30 31
A2 B0 C0 32 33
C1 34 35
C2 36 37
C3 38 39
B1 C0 40 41
C1 42 43
C2 44 45
C3 46 47
我想在每个lvl0索引中获取特殊的lvl1组。在这种情况下,选择列b具有最大值的组,结果可能是这样的:
a b
lvl0 lvl1 lvl2
A0 B1 C0 8 9
C1 10 11
C2 12 13
C3 14 15
A1 B0 C0 16 47
C1 18 49
C2 20 41
C3 22 43
A2 B1 C0 40 41
C1 42 43
C2 44 45
C3 46 47
有没有像df[(('A0','B1'),('A1','B0'),('A2','B1')),:]
这样的索引方法?我尽我所能,谢谢你的帮助。
您可以使用:
df1 = df.reset_index(level=2, drop=True)
mask = df1.index.isin(df1.groupby(level=[0])['b'].idxmax())
df = df[mask]
print (df)
a b
lvl0 lvl1 lvl2
A0 B1 C0 8 9
C1 10 11
C2 12 13
C3 14 15
A1 B0 C0 16 47
C1 18 49
C2 20 41
C3 22 43
A2 B1 C0 40 41
C1 42 43
C2 44 45
C3 46 47
说明:
首先用MultiIndex
删除3级reset_index
,用groupby
删除idxmax
,以获得b
列中的最大值索引:
df1 = df.reset_index(level=2, drop=True)
idx = df1.groupby(level=[0])['b'].idxmax()
print (idx)
lvl0
A0 (A0, B1)
A1 (A1, B0)
A2 (A2, B1)
Name: b, dtype: object
然后通过isin
比较创建布尔掩码:
print (df1.index.isin(idx))
[False False False False True True True True True True True True
False False False False False False False False True True True True]
最后由boolean indexing
过滤:
df = df[df1.index.isin(idx)]
print (df)
a b
lvl0 lvl1 lvl2
A0 B1 C0 8 9
C1 10 11
C2 12 13
C3 14 15
A1 B0 C0 16 47
C1 18 49
C2 20 41
C3 22 43
A2 B1 C0 40 41
C1 42 43
C2 44 45
C3 46 47