首页 > 解决方案 > 如何实现涉及在多列上乘以数字的“if-else”条件

问题描述

我正在将逻辑转换为 python,需要一些帮助。

如果列 A [货币] == CAD,那么我需要将所有列(列 D、E、G)乘以 0.7,这些列的名称中包含字符串“成本”,如果列 A [货币] == USD,那么会有对于 col D、E 和 G 保持不变。

请注意,这是一个示例,名称中有超过 50 个列的成本。

我尝试了以下代码但没有用:

cad_cols = df.filter(regex='cost').columns
df[cad_cols] = np.where(df['currency']=="CAD",*0.7)



currency    name    address prim_cost   sec_cost    sales   overall_cost
cad     a   x       1       8       1   4
cad     b   x       5       3       2   3
usd     d   x       7       2       3   6
usd     e   x       9       4       4   7

标签: pythonpandas

解决方案


筛选选择列

df.loc[df.currency==1,['p','s','o']]*=0.7

推荐阅读