在 Pandas 中访问多索引数据帧时出现 KeyError
KeyError while accessing multi index dataframe in Pandas
我有以下数据框,其中 "Location" 和 "Name" 作为索引。
Location Name Cost Item Purchased
Store 1 Chris 22.5 Dog Food
Kevyn 2.5 Kitty Litter
Store 2 Vinod 5.0 Bird Seed
我可以访问df.loc["Store 1"]
但是 df.loc["Store 1"]["Kevyn"]
给我 KeyError。我做错了什么?
您在此处使用了一些不正确的链式索引,您希望使用类似
的方式对 MultiIndex 的两个级别进行索引
df.loc['Store 1', 'Kevyn']
您需要传递一个元组:
In [100]:
df.loc[('Store 1', 'Kevyn'),:]
Out[100]:
Cost 2.5
Item Purchased Kitty Litter
Name: (Store 1, Kevyn), dtype: object
docs详细介绍了如何索引
我有以下数据框,其中 "Location" 和 "Name" 作为索引。
Location Name Cost Item Purchased
Store 1 Chris 22.5 Dog Food
Kevyn 2.5 Kitty Litter
Store 2 Vinod 5.0 Bird Seed
我可以访问df.loc["Store 1"]
但是 df.loc["Store 1"]["Kevyn"]
给我 KeyError。我做错了什么?
您在此处使用了一些不正确的链式索引,您希望使用类似
的方式对 MultiIndex 的两个级别进行索引df.loc['Store 1', 'Kevyn']
您需要传递一个元组:
In [100]:
df.loc[('Store 1', 'Kevyn'),:]
Out[100]:
Cost 2.5
Item Purchased Kitty Litter
Name: (Store 1, Kevyn), dtype: object
docs详细介绍了如何索引