gpt4 book ai didi

python - 为什么 Pandas DataFrame 切片的索引与其形状不同?

转载 作者:行者123 更新时间:2023-11-28 21:10:24 24 4
gpt4 key购买 nike

我有一个 DataFrame,df1,它是 df 的一部分。 df 是多索引的,形状为 (8,)。 slice 移除了一些 df 的第二层。当我执行 df1.shape 时,它返回 (4,) - 一切都很好 - 但是当我执行 df1.index.levels[0] 时返回 (4,)。怎么会这样?

In [ ]:       
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]


df = pd.DataFrame(np.random.randn(8,2), index=arrays)
df

Out [ ]:
0 1
bar one -0.447155 -0.323073
two 0.115899 -0.015561
baz one -0.272498 1.847073
two -0.399948 -0.264327
foo one 0.169687 -1.708543
two 1.154434 0.878936
qux one 0.535721 0.437186
two -1.203431 0.568412

In [ ]:
df1=df[df[1]>0]

Out [ ]:
0 1
baz one -0.272498 1.847073
foo two 1.154434 0.878936
qux one 0.535721 0.437186
two -1.203431 0.568412

现在是奇怪的地方

In [ ]:
df1=df[df[1]>0]
print(df1.index.levels[0], df1.index.levels[0].shape)

Out [ ]:
Index(['bar', 'baz', 'foo', 'qux'], dtype='object') (4,)

我觉得这很奇怪,因为 df1 中没有显示 bar。这背后的原因是什么?

我猜这与复制/不复制有关,但我不明白为什么。

最佳答案

根据 docs :

Note The repr of a MultiIndex shows ALL the defined levels of an index, even if the they are not actually used. When slicing an index, you may notice this. ...

This is done to avoid a recomputation of the levels in order to make slicing highly performant. If you want to see the actual used levels...

仅使用已用级别重建多索引

df1.index = pd.MultiIndex.from_tuples(df1.index)

关于python - 为什么 Pandas DataFrame 切片的索引与其形状不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com