2017-02-21 215 views
0

我已经采取了数据帧(用初始索引0 ... 9999),并分配由一年这样:熊猫索引异常行为:DF [df.index [0]] => KeyError异常

requests_df = {year : df[df['req_year'] == year] for year in df['req_year'].unique()} 

作为按照惯例,每个子帧保留其自己的索引排序。然后,当试图指数在这些孤立的框架之一(df_yr = requests_df[2015])我得到这个真的很意外的行为:

for idx in df_year.index: 
     qty = frame[idx]['qty_tickets'] 

原因:

KeyError         Traceback (most recent call last) 
/home/user/ve/ml/lib/python3.5/site-packages/pandas/indexes/base.py in get_loc(self, key, method, tolerance) 
    2133    try: 
-> 2134     return self._engine.get_loc(key) 
    2135    except KeyError: 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4433)() 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4279)() 

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13742)() 

pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13696)() 

KeyError: 8666 

思考我的迭代器疯玩,我想一个简单的例子:

df_yr[df_yr.index[0]]

KeyError 

笏。

8666绝对是第一行的索引值:

Int64Index([8666, 8667, 8668, 8669, 8670, 8671, 8672, 8673, 8674, 8675, 
      ... 
      9830, 9831, 9832, 9833, 9834, 9835, 9836, 9837, 9838, 9839], 
      dtype='int64', length=1174) 

索引使用禄,

outframe.loc[8666] 

我虽然依靠df.index值,做工精细。 wat。

df.ix也适用,这是不是太令人惊讶,因为它有内置的回退。

我使用df.index几十个时间没有问题的操作索引。是什么赋予了?

+3

尝试将'qty = frame [idx] ['qty_tickets']'更改为'qty = frame。loc [idx,'qty_tickets']' – jezrael

+1

'df [i]'默认执行基于列标签的索引。 'df.loc [i]'和'df.ix [i]'都执行行索引。 –

+0

@IgorRaush你告诉我我的方式错误!我假设自从'df [2:4]'这样的片就可以工作,并且我已经习惯了掩盖('df [df ['foo'] =='bar]'东西),我忘记了那个简单的行在df已被屏蔽后,索引失败。你介意发布这个答案吗? – DeusXMachina

回答

1

通常,df[index]将执行基于列标签的索引。正如您所注意到的例外是

  • df[slice]将切片行
  • df[boolean_mask]将选择基于掩码

比这两个例外其他行的子集,有消除歧义没有有效的方法df[row_label]df[col_label],所以Pandas使用后一种解释,因为它与“类似字典”的数据框更加一致。 df_yr[df_yr.index[0]]的实验引发错误,因为您正在尝试使用预计有列索引标签的行索引标签。

相反,使用多轴基于标签的索引,为此,语法是

df.loc[row_indexer, col_indexer] 

col_indexer哪里是可选的。 df.loc[df.index[0]]应该工作得很好。在你的代码的破碎部分,使用

frame.loc[idx, 'qty_tickets'] 

(这也是noted by jezrael in the comments)。