我正在根据我之前计算的索引列表设置一列。我还在计算过程中删除了一些索引,所以一些索引不再是我的数据帧的一部分。这个简化的例子展示了现在发生的事情:
df = pd.DataFrame(data=[[1 , 2, False], [4 , 5, False]], columns=["col1", "col2", "col3"], index=[1, 3])
df.loc[[1, 2], 'col3'] = True
显然我收到了一个 KeyError:
KeyError: '[2] not in index'
不幸的是 .loc() 没有提供类似 error="ignore" 的东西。使用 try-catch-block 迭代捕获 KeyError 的列表是唯一的解决方案,还是有更好的方法来做到这一点?
有什么提示吗?谢谢
答案 0 :(得分:1)
您可以使用 .index.intersection()
仅选择“好键”:
good_keys = df.index.intersection([1, 2])
df.loc[good_keys, "col3"] = True
print(df)
打印:
col1 col2 col3
1 1 2 True
3 4 5 False
答案 1 :(得分:0)
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