【问题标题】:How we can define specific columns to multiply it with specifc columns?我们如何定义特定列以将其与特定列相乘?
【发布时间】:2021-05-05 22:55:04
【问题描述】:

我有这样的df

Web     R_Val     B_Cost     R_Total     B_Total
A       20        2           20         1
B       30        3           10         2
C       40        1           30         1

我想以 R_ 开头的列和 B_ 一起相乘,在实际数据中还有更多。这只是虚拟数据,实现这一目标的最佳解决方案是什么?

 Web     R_Val     B_Cost     R_Total     B_Total     R_New       B_New
    A       20        2           20         1
    B       30        3           10         2
    C       40        1           30         1

【问题讨论】:

    标签: python pandas dataframe calculated-columns


    【解决方案1】:

    查看我刚刚发布的关于您其他问题的答案:

    How to multiply specific column from dataframe with one specific column in same dataframe?

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2020-05-09
      • 2023-03-20
      • 2022-11-10
      • 2015-03-23
      相关资源
      最近更新 更多