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

Pandas按多条件筛选行计算新列触发SettingWithCopyWarning如何修正

代码修正方案

错误原因

触发警告的核心原因是你使用了链式索引操作:先通过.loc筛选出行切片后,再用方括号单独选择resi列赋值,pandas无法判定你操作的是原始DataFrame还是临时生成的切片副本,因此抛出安全警告。

修正代码

按照pandas官方推荐的.loc[row_indexer, col_indexer]写法,把列索引直接放到.loc的第二个参数位置,一次完成定位赋值即可消除警告:

raw_data.loc[
    (raw_data['PERMNO'] == 10006) & (raw_data['month'] >= 50) & (raw_data['month'] <= 100),
    'resi'
] = raw_data['RET'] - raw_data['ewretd']

优化建议(可选)

如果DataFrame体量较大,可提前提取筛选掩码、限定右侧计算的行范围,减少不必要的全列计算开销:

# 提前生成筛选掩码
filter_mask = (raw_data['PERMNO'] == 10006) & (raw_data['month'] >= 50) & (raw_data['month'] <= 100)
# 仅对符合条件的行做计算和赋值
raw_data.loc[filter_mask, 'resi'] = raw_data.loc[filter_mask, 'RET'] - raw_data.loc[filter_mask, 'ewretd']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:36:01