Skip to content Skip to sidebar Skip to footer

How To Multiply Specific Column From Dataframe With One Specific Column In Same Dataframe?

I have a dataframe where i need to create new column based on the multiplication of other column with specific column Here is how my data frame looks. df: Brand Price S_Va

Solution 1:

Firstly, to get the columns which you have to multiply, you can use list comprehension and string function startswith. And then just loop over the columns and create new columns by muptiplying with 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

enter image description here

Solution 2:

Since you did not added and example of the output. This might be what you are looking for:

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_']
forprefixin pre_fixes:
    coltocal = [col forcolin dfr.columns if col.startswith(prefix)]
    forcolin coltocal:
        dfr.loc[:,col+'_new'] = dfr.price*dfr[col]
dfr

    Brand   price   S_Value S_Factor    S_Value_new S_Factor_new
0   A   102220201   B   204180202   C   302160303   D   401240804   E   501150505   F   10111010

Just add as many prefixes you have to pre_fixes (use come to separate them)

Post a Comment for "How To Multiply Specific Column From Dataframe With One Specific Column In Same Dataframe?"