You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理Python中的SettingWithCopyWarning警告?附鸢尾花分类代码

解决Pandas SettingWithCopyWarning警告的方案

你遇到的SettingWithCopyWarning是因为代码中使用了链式索引(比如df2['Correct_Values'][i]),Pandas无法确定你修改的是原始DataFrame还是它的临时视图,因此抛出警告。以下是几种可靠的解决方式:

方法一:使用向量化操作(推荐)

完全抛弃循环,用Pandas的向量化运算直接生成布尔列,这是最符合Pandas设计理念的高效写法,同时彻底消除警告:

# 先创建基础DataFrame
df2 = pd.DataFrame({
    'Test_Values': y_test.values,
    'Predicted_Values': y_pred
})
# 直接通过布尔比较生成结果列
df2['Correct_Values'] = df2['Test_Values'] == df2['Predicted_Values']
# 取反得到错误标记列
df2['Wrong_Values'] = ~df2['Correct_Values']

方法二:用.loc明确索引(保留循环场景)

如果坚持要使用循环逻辑,改用.loc[row, column]的索引方式,明确告诉Pandas操作的是原始DataFrame的指定位置,避免视图/副本的歧义:

df2 = pd.DataFrame({
    'Test_Values': y_test.values,
    'Predicted_Values': y_pred,
    'Correct_Values': False,
    'Wrong_Values': False
})

for i in df2.index:
    if df2.loc[i, 'Test_Values'] == df2.loc[i, 'Predicted_Values']:
        df2.loc[i, 'Correct_Values'] = True
    else:
        df2.loc[i, 'Wrong_Values'] = True

补充说明

  • 向量化操作的执行效率远高于循环,尤其是处理大规模数据集时,优先推荐使用这种方式。
  • 如果你的DataFrame是从其他DataFrame切片得到的(而非新建),可以在创建时加上.copy()确保得到独立副本,避免潜在的视图问题:df2 = original_df[cols].copy()

内容的提问来源于stack exchange,提问作者Karthik Goud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 00:10:10