在使用 xs 方法时,我正在努力获得正确的(仅限于选择)索引通过 pandas 在我的数据框中选择特定数据。让我演示一下我在做什么:
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
