我已經採取了數據幀(用初始索引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幾十個時間沒有問題的操作索引。是什麼賦予了?
嘗試將'qty = frame [idx] ['qty_tickets']'更改爲'qty = frame。loc [idx,'qty_tickets']' – jezrael
'df [i]'默認執行基於列標籤的索引。 'df.loc [i]'和'df.ix [i]'都執行行索引。 –
@IgorRaush你告訴我我的方式錯誤!我假設自從'df [2:4]'這樣的片就可以工作,並且我已經習慣了掩蓋('df [df ['foo'] =='bar]'東西),我忘記了那個簡單的行在df已被屏蔽後,索引失敗。你介意發佈這個答案嗎? – DeusXMachina