Python 在数据帧上使用.loc()处理KeyError
我正在根据我前面计算的索引列表设置一列。我还在计算过程中删除了一些索引,因此一些索引不再是我的数据帧的一部分。此简化示例显示了现在发生的情况:Python 在数据帧上使用.loc()处理KeyError,python,pandas,dataframe,Python,Pandas,Dataframe,我正在根据我前面计算的索引列表设置一列。我还在计算过程中删除了一些索引,因此一些索引不再是我的数据帧的一部分。此简化示例显示了现在发生的情况: df = pd.DataFrame(data=[[1 , 2, False], [4 , 5, False]], columns=["col1", "col2", "col3"], index=[1, 3]) df.loc[[1, 2], 'col3'] = True 显然,我遇到了一个关键
df = pd.DataFrame(data=[[1 , 2, False], [4 , 5, False]], columns=["col1", "col2", "col3"], index=[1, 3])
df.loc[[1, 2], 'col3'] = True
显然,我遇到了一个关键错误:
KeyError: '[2] not in index'
不幸的是,loc()不提供类似error=“ignore”的内容。用try-catch块在列表上迭代捕捉keyrerror是唯一的解决方案还是有更好的方法
有什么提示吗?谢谢您可以使用
.index.intersection()
仅选择“好键”:
印刷品:
col1 col2 col3
1 1 2 True
3 4 5 False
reindex
在以前不存在索引值的位置放置空行或列
df = df.reindex([1, 2, 3])
df.loc[[1, 2], 'col3'] = True
df
col1 col2 col3
1 1.0 2.0 True
2 NaN NaN True
3 4.0 5.0 False
听起来不错,谢谢。
df = df.reindex([1, 2, 3])
df.loc[[1, 2], 'col3'] = True
df
col1 col2 col3
1 1.0 2.0 True
2 NaN NaN True
3 4.0 5.0 False