部分标签索引上的多索引键错误

2024-09-29 20:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重现pandasuser guide中的“轴上的基本索引和多索引”部分

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
print(df)
print(df['bar'])

我看不出为什么我的代码与用户指南中显示的代码有什么不同。我有一个键错误:最后一行是“bar”


Tags: 代码dataframedffoonpbarbazone
2条回答

您所参考的用户指南(this)部分是针对数据帧的列是多索引的情况。当索引为多索引时,您应该查看此part

要访问bar,您应该执行以下操作:

print(df.loc["bar"])

如果要访问bar,则需要使用loc,或将其转置,因为bar不在列中:

>>> df.loc['bar']
            0         1         2         3
one  0.888182  0.066730  1.397408 -0.550522
two -0.258916 -1.859689 -0.294348 -0.646791

转置:

>>> df.T['bar']

        one       two
0  0.888182 -0.258916
1  0.066730 -1.859689
2  1.397408 -0.294348
3 -0.550522 -0.646791

编辑:

如前所述,在注释中非常有用,如果您想保留多索引:

>>> df.xs('bar',drop_level=False)
                0         1         2         3
bar one -0.857271  1.271094  0.565691 -0.523375
    two  0.826911  0.244787  0.991158 -0.484815

尽管这取决于您的用例,但看起来您实际上需要:

>>> arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
>>> df = pd.DataFrame(np.random.randn(4, 8), columns=arrays)

>>> df

        bar                 baz                 foo                 qux          
        one       two       one       two       one       two       one       two
0  1.600817 -1.420187 -0.798078  1.632550 -0.737740 -1.036077 -1.034157  1.576907
1  0.111148 -1.830283  0.507195 -0.042425  0.260859 -1.600065 -0.449921  0.657582
2 -1.054305 -0.885309  0.325678 -0.253772 -0.444176  0.331933  0.332281  0.127738
3  1.071590  0.947280 -0.973616  0.677141  0.133742  1.352731 -0.210731  2.079073

# Then you can do either df['bar'] directly

参考资料:

  1. ^{}

  2. ^{}

  3. ^{}

  4. 你问题中的链接。我建议你仔细检查一下,解释得很好

相关问题 更多 >

    热门问题