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

Pandas合并DF后按条件计算新列不生效且报SettingWithCopyWarning怎么办

问题根因

  • 你通过df.iloc遍历拿到的行对象是原数据的视图副本,直接对行对象赋值不会作用到原DataFrame,同时会触发SettingWithCopyWarning警告
  • 逐行遍历的写法不符合Pandas向量化操作规范,数据量较大时执行效率极低

最优实现方案

推荐直接使用np.where做条件判断,全程向量化操作,一行代码即可完成需求,不会出现修改不生效的问题:

import numpy as np

# 匹配你原有代码的判断逻辑:show_id等于count时取show_id,否则取两列之和
merged_by_country["total_shows"] = np.where(
    merged_by_country["show_id"] == merged_by_country["count"],
    merged_by_country["show_id"],
    merged_by_country["show_id"] + merged_by_country["count"]
)

如果你实际需求是判断country和first_country是否相等再做计算,只需把条件替换为merged_by_country["country"] == merged_by_country["first_country"]即可。

循环写法修正(不推荐,仅做原理参考)

如果要保留循环写法,需要通过索引定位直接修改原DataFrame的对应位置:

test = merged_by_country.copy()

def set_shows(df):
    for idx, row in df.iterrows():
        if row["show_id"] == row["count"]:
            df.loc[idx, "total_shows"] = row["show_id"]
        else:
            df.loc[idx, "total_shows"] = row["show_id"] + row["count"]
    return df

test = set_shows(test)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:57:02