【发布时间】:2022-01-18 13:41:25
【问题描述】:
我正在尝试循环遍历数据帧以比较 i 和 i+1 索引,如下所示:
d = {'col1': [1, 2,0,55,12,1, 3,1,56,13], 'col2': [3,4,44,34,46,2,3,43,35,47], 'col3': ['A','A','A','B','B','A','B','B','B','B'] }
df = pd.DataFrame(data=d)
df
for index, row in df.iterrows():
if df.at[index,"col3"] != df.at[index+1,"col3"]:
print('True')
else:
print("false")
我收到此错误:
false
false
True
false
True
True
false
false
false
KeyError Traceback(最近 最后打电话) 在 () 3 4 用于索引,df.iterrows() 中的行: ----> 5 如果 df.at[index,"col3"] != df.at[index+1,"col3"]: 6 打印('真') 其他 7 个:
in getitem(自我,钥匙) 2140 第2141章 -> 2142 返回 self.obj._get_value(*key, takeable=self._takeable) 2143 2144 def setitem(自我、键、值):
2538 try: -> 2539 return engine.get_value(series._values, index) 2540 except (TypeError, ValueError): 2541 pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 10
【问题讨论】:
标签: python pandas indexing keyerror