how to multiply multiple columns by a column in Pandas

Question:

I would like to have:

df[['income_1', 'income_2']] * df['mtaz_proportion']

return those columns multiplied by df['mtaz_proportion']

so that I can set

df[['mtaz_income_1', 'mtaz_income_2']] = 
df[['income_1', 'income_2']] * df['mtaz_proportion']

but instead I get:

income_1    income_2    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  
0   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ...
1   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ...
2   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ...

ect…

what simple thing am I missing?

Thank you!

Asked By: tapzx2

||

Answers:

use multiply method and set axis="index":

df[["A", "B"]].multiply(df["C"], axis="index")
Answered By: HYRY

Another way of writing the answer of HYRY:

df.loc[:,['A', 'B']] = df.loc[:,['A', 'B']].multiply(df.loc[:, 'C'], axis="index")
Answered By: Matthi9000

Convert both factors to numpy arrays using to_numpy:

df.loc[:, ['D', 'E']] = df[['A', 'B']].to_numpy() * df[['C']].to_numpy()
Answered By: rachwa
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.