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

标签 python pandas indexing dataframe

我有一个 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/

相关文章:

python - 尽管重复,Pandas仍显示jupyter笔记本中的所有索引标签

python - 合并两个具有重叠索引的数据框,保留左侧数据框中的列值

python - pandas df.apply 返回一系列相同列表(如 map ),其中应返回一个列表

将 LEFT JOIN 与 OR 结合使用时,MySQL 查询会忽略索引?

mysql - 索引如何帮助在MySQL中快速搜索数据

python - 如何提取特定类别之前的最后 3 个索引号

python - 如何通过IF语句简化变量赋值

python - DRF 的 CurrentUserDefault 未返回用户

python - reshape 数据框并聚合值

python - Pandas 使用什么规则来生成 View 和副本?