2017-02-21 214 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)。