how to multiply multiple columns by a column in Pandas
Asked Answered
C

3

85

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!

Cum answered 28/3, 2014 at 1:56 Comment(0)
D
131

use multiply method and set axis="index":

df[["A", "B"]].multiply(df["C"], axis="index")
Derangement answered 28/3, 2014 at 2:1 Comment(5)
Just a caveat: df["C"] may not behave as expected if passed as a DataFrame like df[["C"]]Odontalgia
The code works but the df doesn't hold it. (-> print(df) just gives the original df afterwards) Instead do: df[["A", "B"]] = df[["A", "B"]].multiply(df["C"], axis="index") and then columns A and B in the df hold the changesGemination
Do not know, but somehow all the row-columns become NaN after multiplication.Cyrene
@Cyrene It happened to me as well but the issue got resolved by using axis='index'.Felicle
Nice. It seems to work with a normal Python list too, instead of df['C']. With axis=0Kono
G
4

Another way of writing the answer of HYRY:

df.loc[:,['A', 'B']] = df.loc[:,['A', 'B']].multiply(df.loc[:, 'C'], axis="index")
Gemination answered 29/8, 2020 at 14:53 Comment(0)
S
2

Convert both factors to numpy arrays using to_numpy:

df.loc[:, ['D', 'E']] = df[['A', 'B']].to_numpy() * df[['C']].to_numpy()
Strongbox answered 28/5, 2022 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.