Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 索引数据帧,其中(多)索引仅包含部分数据帧';s级_Python_Pandas_Multi Index - Fatal编程技术网

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)