Search code examples
pythonpandasdataframecalculated-columns

How we can define specific columns to multiply it with specifc columns?


I have df like this

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

I would like to multiply the column started with R_ together and B_ together and in real data there are many more. This is just dummy data, what could be the best solution to achieve this?

 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

Solution

  • Check the answer I just posted on your other question:

    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