4 g 0 0 00
我有一个熊猫数据框df
:-
使用切片只获得作为字典中键的列,然后乘以它,每行聚合为sum
,multiply
通过COST:
df['TOTAL_COST'] = df[list(total_cost)].mul(total_cost).sum(axis=1).mul(df['COST'])
或者,将字典转换为Series(不匹配的列将变成NaN):
df['TOTAL_COST'] = df.mul(pd.Series(total_cost)).sum(axis=1).mul(df['COST'])
输出:
ID COST 1F 2F 3F 4G TOTAL_COST
0 1 362 0 1 1 1 28.236
1 2 269 0 1 0 0 8.070
2 3 346 1 1 1 1 43.250
3 4 342 0 0 0 0 0.000