pandas multiindex selecting...如何获得正确的(仅限选择)索引

pandas multiindex selecting...how to get the right (restricted to selection) index

当我使用方法 xs by pandas 到 select 我的数据框中的特定数据时,我正在努力获得正确的(仅限于 selection)索引.让我演示一下我在做什么:

print(df)
                                                             value
idx1              idx2          idx3         idx4  idx5            
10                2.0           0.0010          1     2        6.0  ...   
                                                2     3        6.0  ...   
...
                                                7     8        6.0  ...   
                                                8     9        6.0  ...  
20                2.0           0.0010          1     2        6.0  ...  
                                                2     3        6.0  ...  
...
                                                18    19       6.0  ...  
                                                19    20       6.0  ...  

# get dataframe for idx1 = 10, idx2 = 2.0, idx3 = 0.0010 
print(df.xs([10,2.0,0.0010]))

             value
idx4  idx5            
1     2        6.0  ...   
2     3        6.0  ...   
3     4        6.0  ...     
4     5        6.0  ...     
5     6        6.0  ...     
6     7        6.0  ...     
7     8        6.0  ...   
8     9        6.0  ...  

# get the first index list of this part of the dataframe
print(df.xs([10,2.0,0.0010]).index.levels[0])

[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,18, 19]

所以我不明白,为什么即使我们将数据帧限制在 idx4 只取 1 到 8 的值的部分,为什么返回 idx4 中出现的完整值列表。是我使用 index 方法错误?

这是一个已知的功能,不是错误。 pandas 保留所有索引信息。您可以通过 labels 属性确定表达的级别和位置。

如果您希望创建一个新的索引,并且只包含与您刚刚创建的切片相关的信息,您可以这样做:

df_new = df.xs([10,2.0,0.0010])
idx_new = pd.MultiIndex.from_tuples(df_new.index.to_series(),
                                    names=df_new.index.names)
df_new.index = idx_new