How can I multiply columns whose name begins with a certain string by another column

Viewed 211

I'm trying to multiply certain columns within a data frame by one specific column. While the specific column will always be the same, the names and number of the other columns will vary so I cannot specify those column names except for what the string they begin with. I have been trying to use .mul but have had trouble getting it to work. Any way I can do this?

Original DF

ID # Column To Multiply By ABC Column1 ABC Column2
12 2 1 2
13 3 1 2
14 4 1 2

Desired DF

ID # Column To Multiply By ABC Column1 ABC Column2
12 2 2 4
13 3 3 6
14 4 4 8

I tried using the line below but am met with a syntax error:

df2 = df1.loc[:, df1.columns.str.startswith('ABC').mul(df1.Column to Multiply By, axis=0)

1 Answers

This should do the work:

df2 = df1
df2['ABC Column1'] = df1['Column To Multiply By'] * df1['ABC Column1']  
df2['ABC Column2'] = df1['Column To Multiply By'] * df1['ABC Column2']

Edit: If the name of ABC columns changes but the prefix is constant, this should work:

df[df.columns[pd.Series(df.columns).str.startswith('ABC')]] = df[df.columns[pd.Series(df.columns).str.startswith('ABC')]].multiply(df['Column To Multiply By'], axis='index')
Related