我已经采取了数据帧(用初始索引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