how to multiply multiple columns by a column in Pandas

PythonPandas

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

use multiply method and set axis="index":

df[["A", "B"]].multiply(df["C"], axis="index")

Solution 2 - Python

Another way of writing the answer of HYRY:

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

Solution 3 - Python

Convert both factors to numpy arrays using to_numpy:

df.loc[:, ['D', 'E']] = df[['A', 'B']].to_numpy() * df[['C']].to_numpy()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiontapzx2View Question on Stackoverflow
Solution 1 - PythonHYRYView Answer on Stackoverflow
Solution 2 - PythonMatthi9000View Answer on Stackoverflow
Solution 3 - PythonrachwaView Answer on Stackoverflow