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

如何将pandas DataFrame中含extra的列与对应前一列的数值求和

解决方案

该需求在pandas中可以直接实现,以下是可直接运行的完整代码:

1. 构造示例DataFrame(测试用,你可以替换成自己的数据集)

import pandas as pd

# 示例数据和你给出的结构完全一致
data = {
    "id": [0, 1, 2],
    "laptops": [54, 33, 82],
    "laptops extra": [18, 9, 61],
    "battery": [108, 48, 98],
    "cables": [54, 20, 67],
    "monitor": [28, 10, 21],
    "monitor extra": [12, 4, 9]
}
df = pd.DataFrame(data)

2. 核心处理逻辑

# 筛选所有列名包含extra的列的位置索引
extra_col_indexes = [idx for idx, col_name in enumerate(df.columns) if "extra" in col_name.lower()]

# 倒序遍历处理,避免删除列后索引偏移导致错误
for col_idx in reversed(extra_col_indexes):
    # 跳过extra列是第一列的异常场景
    if col_idx < 1:
        continue
    # 取extra列的前一列索引
    prev_col_idx = col_idx - 1
    # 前一列的值加上对应extra列的值
    df.iloc[:, prev_col_idx] += df.iloc[:, col_idx]
    # 移除已经处理完的extra列,不需要删除可以注释掉这行
    df.drop(df.columns[col_idx], axis=1, inplace=True)

3. 效果说明

处理后:

  • 原laptops列的值会和laptops extra列的值相加,得到新的laptops列
  • 原monitor列的值会和monitor extra列的值相加,得到新的monitor列
  • 所有带extra标识的列会被自动删除,最终只保留清洗后的核心列
    该方案兼容任意数量的带extra标识的列,只要extra列和要合并的前一列是紧邻关系就可以正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:45:01