【问题标题】:How to multiply specific column from dataframe with one specific column in same dataframe?如何将数据框中的特定列与同一数据框中的一个特定列相乘?
【发布时间】:2023-03-20 19:07:01
【问题描述】:

我有一个数据框,我需要根据其他列与特定列的乘法来创建新列

这是我的数据框的外观。

df:

Brand     Price      S_Value        S_Factor
A         10          2             2
B         20          4             1
C         30          2             1
D         40          1             2
E         50          1             1
F         10          1             1

我想将列 Value 和 Factor 与 Price 相乘以获得新列。我可以手动完成,但我有很多列,并且都以特定前缀开头,我需要相乘...这里我使用了S_,这意味着我需要将所有以S_开头的列相乘

这将是所需的输出列

Brand     Price      S_Value        S_Factor       S_Value_New       S_Factor_New
A         10          2             2
B         20          4             1
C         30          2             1
D         40          1             2
E         50          1             1
F         10          1             1

【问题讨论】:

标签: python pandas multiple-columns calculated-columns


【解决方案1】:

首先,要获得需要相乘的列,可以使用列表推导和字符串函数startswith。然后只需循环列并通过使用Price 复制来创建新列

multiply_cols = [col for col in df.columns if col.startswith('S_')]
for col in multiply_cols:
    df[col+'_New'] = df[col] * df['Price']

df

【讨论】:

    【解决方案2】:

    由于你没有添加和输出示例。这可能是您正在寻找的:

    dfr = pd.DataFrame({
        'Brand' : ['A', 'B', 'C', 'D', 'E', 'F'], 
        'price'  : [10, 20, 30, 40, 50, 10],
        'S_Value'  : [2,4,2,1,1,1],
        'S_Factor'  : [2,1,1,2,1,1]
    })
    
    pre_fixes = ['S_']
    for prefix in pre_fixes:
        coltocal = [col for col in dfr.columns if col.startswith(prefix)]
        for col in coltocal:
            dfr.loc[:,col+'_new'] = dfr.price*dfr[col]
    dfr
    
        Brand   price   S_Value S_Factor    S_Value_new S_Factor_new
    0   A   10  2   2   20  20
    1   B   20  4   1   80  20
    2   C   30  2   1   60  30
    3   D   40  1   2   40  80
    4   E   50  1   1   50  50
    5   F   10  1   1   10  10
    

    只需在pre_fixes 中添加尽可能多的前缀(使用来分隔它们)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 2015-04-07
      相关资源
      最近更新 更多