64

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
  • 841
  • 1
  • 7
  • 11

3 Answers3

99

use multiply method and set axis="index":

df[["A", "B"]].multiply(df["C"], axis="index")
HYRY
  • 89,863
  • 23
  • 181
  • 185
  • 1
    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
  • 6
    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
2

Another way of writing the answer of HYRY:

df.loc[:,['A', 'B']] = df.loc[:,['A', 'B']].multiply(df.loc[:, 'C'], axis="index")
David Arenburg
  • 89,637
  • 17
  • 130
  • 188
Matthi9000
  • 814
  • 1
  • 12
  • 26
0

Convert both factors to numpy arrays using to_numpy:

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