82

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!

tapzx2
  • 1,021
  • 1
  • 8
  • 11

3 Answers3

125

use multiply method and set axis="index":

df[["A", "B"]].multiply(df["C"], axis="index")
HYRY
  • 94,853
  • 25
  • 187
  • 187
  • 2
    Just a caveat: `df["C"]` may not behave as expected if passed as a DataFrame like `df[["C"]]` – Alexander McFarlane Jul 03 '18 at 15:48
  • 7
    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 changes – Matthi9000 Aug 29 '20 at 14:44
  • Do not know, but somehow all the row-columns become NaN after multiplication. – EMT Mar 25 '22 at 15:13
  • @EMT It happened to me as well but the issue got resolved by using `axis='index'`. – Bhanuday Sharma Nov 11 '22 at 09:04
4

Another way of writing the answer of HYRY:

df.loc[:,['A', 'B']] = df.loc[:,['A', 'B']].multiply(df.loc[:, 'C'], axis="index")
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Matthi9000
  • 1,156
  • 3
  • 16
  • 32
2

Convert both factors to numpy arrays using to_numpy:

df.loc[:, ['D', 'E']] = df[['A', 'B']].to_numpy() * df[['C']].to_numpy()
rachwa
  • 1,805
  • 1
  • 14
  • 17