Python 索引数据帧,其中(多)索引仅包含部分数据帧';s级
我希望获取一个具有多索引的数据帧,并使用另一个(多)索引对其进行索引,该索引包含数据帧级别的严格子集。数据帧中不在其他(多)索引中的级别应返回所有行。例如:Python 索引数据帧,其中(多)索引仅包含部分数据帧';s级,python,pandas,multi-index,Python,Pandas,Multi Index,我希望获取一个具有多索引的数据帧,并使用另一个(多)索引对其进行索引,该索引包含数据帧级别的严格子集。数据帧中不在其他(多)索引中的级别应返回所有行。例如: >>> df col num chr 1 a 0.845402 b 0.099432 c 0.507409 2 a 0.684363 b 0.582436 c 0.666528 >>> df['col
>>> df
col
num chr
1 a 0.845402
b 0.099432
c 0.507409
2 a 0.684363
b 0.582436
c 0.666528
>>> df['col'].unstack('chr').mean()
chr
a 0.764883
b 0.340934
c 0.586968
dtype: float64
>>> df['col'].unstack('chr').mean().nsmallest(2)
chr
b 0.340934
c 0.586968
dtype: float64
>>> df['col'].unstack('chr').mean().nsmallest(2).index
Index(['b', 'c'], dtype='object', name='chr')
现在,我想返回'chr'
级别中包含'b'
或'c'
的df
的所有行,以及'num'
级别中的任何值。此外,我想尝试同样的方法,在最后一步中返回的索引是多索引
(即当df
的索引有两个以上级别时):
我想选择
df
的所有行,其索引包含('b','bar')
或('c','baz')
,在最后两个级别和'num'
级别中的任何值。我只能使用获取级别值和isin
s=df['col'].mean(level=[1,2]).nsmallest(2).index.tolist()
df[pd.Series(list(zip(df.index.get_level_values(1),df.index.get_level_values(2)))).isin(s).values]
Out[163]:
col
num chr foo
1 b bar 0.240376
c baz 0.265628
2 b bar 0.729979
c baz 0.821503
我认为最干净的解决方案可能是单独检索所需的行,并pd.concat
。对于索引
解决方案:
idx = df['col'].unstack(['chr', 'foo']).mean().nsmallest(2).index
selected = pd.concat([df.xs(label, level=idx.name, drop_level=False)
for label in idx],
axis=0)
当idx
是一个多索引时,使用level=idx.names
。Yikes。。。希望有一个更地道的说法solution@BallpointBen为什么不重置索引()?多重索引仍在开发中,因此可能会有更多潜在问题
idx = df['col'].unstack(['chr', 'foo']).mean().nsmallest(2).index
selected = pd.concat([df.xs(label, level=idx.name, drop_level=False)
for label in idx],
axis=0)