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

Python pandas如何对指定列的特定行执行叠加运算

实现步骤与代码

你可以直接用pandas的标签索引+数值运算完成需求,核心代码逻辑如下:

import pandas as pd

# 你自己的读表逻辑替换这行即可
# df = pd.read_csv("你的文件路径.csv")

# 定义要操作的数值列
calc_cols = ["A", "B", "C", "D"]

# 提取unique_string1对应列的数值并除以4
str1_values = df.loc[df["Title"] == "unique_string1", calc_cols].div(4).iloc[0]

# 叠加到unique_string2对应的列
df.loc[df["Title"] == "unique_string2", calc_cols] += str1_values

# 如果不需要保留原unique_string1的行,取消注释下行即可
# df = df[df["Title"] != "unique_string1"]

示例运行效果

你给出的样例数据运行后,unique_string2对应的数值列结果如下:

TitleDescriptionABCD
unique_string26.52.2556.5

注意事项

  • 如果你的场景中Title列可能存在多个unique_string1的匹配行,可将.iloc[0]替换为.sum(),会自动把所有匹配行的数值汇总后再做除法叠加
  • 如果你需要最终的数值保持整数类型,可以在运算末尾加.astype(int)做强制类型转换
  • 运算前可以先加断言校验两个目标字符串都存在,避免报错:
    assert df["Title"].isin(["unique_string1", "unique_string2"]).sum() == 2, "目标Title不存在或重复"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:36:03