查询多索引的pandas数据帧

问题描述 投票:1回答:2

对于给定的数据框架df,例如

df = pd.DataFrame({'last_name': ['Clinton', 'Clinton', 'Bush', 'Bush', 'Obama'], 'first_name': ['Bill', 'Hillary', 'George Herbert Walker', 'George Walker', 'Barack']}).set_index(['last_name', 'first_name'])

我无法查询数据帧,如

df.loc['last_name', :] ... # or
df.xs('last_name') ...

因为它失败了(KeyError: 'last_name')。我认为它应该像in this blog post about a demonstration of simple uses of MultiIndex描述的那样工作。

我错过了什么?

pandas dataframe multi-index
2个回答
1
投票

以下是一些选项:

使用查询,(由于列命名限制而不灵活):

df.query('last_name == "Clinton"')

将.loc与axis参数一起使用:

df.loc(axis=0)["Clinton",:]

使用.xs返回数据帧的一部分

df.xs('Clinton')

将get_level_values与布尔索引一起使用:

df[df.index.get_level_values(0) == "Clinton"]

1
投票

您的指令查找行的索引,称为“last_name”。该错误告诉您给定的索引不存在。

df.loc['Clinton','Bill']将返回对应于'Clinton,Bill'的行

df.loc['Clinton',:]返回任何Clintons的行

© www.soinside.com 2019 - 2024. All rights reserved.