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

如何批量创建新列并基于现有列与Reach列计算填充值?

高效批量生成DataFrame新列的方法

问题场景

我有如下结构的DataFrame:

Year      Col1  Col2  Col3  Col4 ......Col64  Reach
2019       12   17     11   11                 10
2020       10   20     21   33                 10
2021       19   15     22   32                 10
2022       26   9      16   12                 10

需要为每个ColX列批量生成对应的ColX Value列,值为ColX * Reach,手动编写64次重复代码效率极低,求高效实现方案。


解决方案

以下三种方法都能实现批量操作,无需重复编写代码:

方法1:循环遍历目标列

先筛选出所有需要处理的Col开头列,再循环生成新列:

import pandas as pd

# 筛选所有Col开头的列,也可直接指定范围:cols = [f'Col{i}' for i in range(1, 65)]
cols = [col for col in df.columns if col.startswith('Col')]

for col in cols:
    df[f'{col} Value'] = df[col] * df['Reach']

方法2:向量化批量计算后合并

利用Pandas的向量化运算,一次性计算所有新列,再合并回原DataFrame,大数据量下效率更高:

import pandas as pd

cols = [col for col in df.columns if col.startswith('Col')]

# 批量计算所有新列的值
new_columns = df[cols].mul(df['Reach'], axis=0)
# 给新列重命名
new_columns.columns = [f'{col} Value' for col in cols]
# 合并到原DataFrame
df = pd.concat([df, new_columns], axis=1)

方法3:使用assign批量生成

通过字典推导式生成新列的键值对,传给assign方法一步完成:

import pandas as pd

cols = [col for col in df.columns if col.startswith('Col')]

df = df.assign(**{f'{col} Value': df[col] * df['Reach'] for col in cols})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:21:03