【问题标题】:KeyError when indexing on a pandas MultiIndex DataFrame在 Pandas MultiIndex DataFrame 上建立索引时出现 KeyError
【发布时间】:2019-06-02 23:59:00
【问题描述】:

文档中的以下示例按预期工作:

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

但是,对于这个例子,从我的数据来看,这样的索引会引发一个错误:

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'

我做错了什么?

【问题讨论】:

    标签: python pandas dataframe multi-index


    【解决方案1】:

    只需使用loc:

    df.loc['alice']
    
               client_id
    2018-01-29         1
    

    pandas 不清楚“alice”是否是 df 的列。通过该系列,很明显对 __getitem__ 的调用正在访问索引。


    其他替代方案(根据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
    

    【讨论】:

      猜你喜欢
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2013-03-13
      • 2023-04-08
      • 2017-01-07
      • 2015-07-19
      • 2012-10-02
      相关资源
      最近更新 更多