[英]KeyError when indexing on a pandas MultiIndex DataFrame
The following example from the docs works as expected:文档中的以下示例按预期工作:
s = pd.Series([1, 2, 3, 4, 5, 6],index=pd.MultiIndex.from_product([["A", "B"], ["c", "d", "e"]]))
s['A']
c 1
d 2
e 3
However, for this example, from my data, such indexing raises an error:但是,对于此示例,根据我的数据,此类索引会引发错误:
df = pd.DataFrame({'client_id': {('foo', '2018-01-29'): '1',
('bar', '2018-01-29'): '1',
('baz', '2018-01-29'): '1',
('alice', '2018-01-29'): '1',
('bob', '2018-01-29'): '1'}})
df['alice']
KeyError: 'alice'
What am I doing wrong?我究竟做错了什么?
Just use loc
:只需使用
loc
:
df.loc['alice']
client_id
2018-01-29 1
It is not clear to pandas whether "alice" is a column or not with df
. pandas 不清楚“alice”是否是
df
的列。 With the series, it is clear a call to __getitem__
is accessing the index.对于该系列,很明显对
__getitem__
的调用正在访问索引。
Other alternatives (as per How do I slice or filter MultiIndex DataFrame levels? ):其他替代方案(根据How do I slice or filter MultiIndex DataFrame levels? ):
df.loc(axis=0)['alice']
client_id
2018-01-29 1
df.xs('alice')
client_id
2018-01-29 1
df.query('ilevel_0 == "alice"')
client_id
alice 2018-01-29 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.