如何批量为DataFrame生成Coln*(Coln Volume)/Coln Value结果列?
批量计算并新增DataFrame列
问题描述
我有如下结构的DataFrame:
Col1 Col2 Col3.... Col64 Col1 Volume Col2 Volume....Col64 Volume.... Col1 Value Col2 Value...Col 64 Value 2 3 4 5 5 7 9 3 5 3 4 5 11 8 6 5 6 5 5 3 4 6 10 11 5 3 4
需要逐行对每个n执行计算:(Coln × Coln Volume) ÷ Coln Value,将结果存入新列Coln Result并追加到原DataFrame中。示例输出如下:
Col1 Result Col2 Result 3.33 4.2 6 4.8 16.6 8.25 ...
手动操作耗时过长,请问如何实现该批量运算?
解决方案
方法一:循环遍历基础列(直观易读)
先提取所有基础列(Col1到Col64),再循环计算每一列的结果:
import pandas as pd # 假设你的DataFrame已加载为df base_cols = [col for col in df.columns if 'Volume' not in col and 'Value' not in col] for col in base_cols: # 匹配对应的Volume和Value列 vol_col = f"{col} Volume" val_col = f"{col} Value" # 计算结果并新增列 df[f"{col} Result"] = (df[col] * df[vol_col]) / df[val_col] # 可选:保留两位小数对齐示例格式 df[f"{col} Result"] = df[f"{col} Result"].round(2)
方法二:向量化运算(高效适合大数据)
利用Pandas的筛选和广播特性,避免循环,性能更优:
import pandas as pd # 拆分三类列,统一列名前缀 base = df.filter(regex='^Col\d+$') volume = df.filter(regex='Volume$').rename(columns=lambda x: x.replace(' Volume', '')) value = df.filter(regex='Value$').rename(columns=lambda x: x.replace(' Value', '')) # 批量计算结果 result_df = (base * volume) / value # 重命名结果列 result_df.columns = [f"{col} Result" for col in result_df.columns] # 合并回原DataFrame df = pd.concat([df, result_df], axis=1) # 可选:保留两位小数 df = df.round({col:2 for col in result_df.columns})
两种方法都能自动生成所有Coln Result列并追加到原DataFrame中,无需手动重复操作。
内容的提问来源于stack exchange,提问作者Jahrakal
相关产品推荐
相关产品推荐

