簡體   English   中英

在 dataframe 上使用 .loc() 處理 KeyError

[英]Handle KeyError using .loc() on dataframe

我正在根據我之前計算的索引列表設置一列。 我還在計算過程中刪除了一些索引,所以一些索引不再是我的 dataframe 的一部分。 這個簡化的示例顯示了現在正在發生的事情:

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" 的功能。 將迭代列表捕獲 KeyError 與 try-catch-block 唯一的解決方案還是有更好的方法來做到這一點?

有什么提示嗎? 謝謝

您可以使用.index.intersection()到 select 只有“好鑰匙”:

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

reindex

將 null 行或列放置在以前不存在索引值的位置。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM