Multiply DataFrame by Different shape DataFrame (or series)
Asked Answered
H

2

5

I have this DataFrame like this:

1  2  1  3  1  4
2  4  5  1  1  4
1  3  5  3  1  4
1  3  1  3  1  4

Another like this

1  1  0  0  0  0

I want to multiply them such as that I get

1  2  0  0  0  0
2  4  0  0  0  0
1  3  0  0  0  0
1  3  0  0  0  0

So what's happening is that every column with a 1 in the second df multiplies every value by one and every column with a zero changes all columns in the first dataframe by 0.

Highkey answered 12/10, 2018 at 2:4 Comment(0)
I
6

It's probably easiest to use the underlying arrays, and let numpy do it's broadcasting magic:

>>> df1.values * df2.values
array([[1, 2, 0, 0, 0, 0],
       [2, 4, 0, 0, 0, 0],
       [1, 3, 0, 0, 0, 0],
       [1, 3, 0, 0, 0, 0]])

You can put it back into a dataframe with the same columns as df1 using:

>>> pd.DataFrame(df1.values * df2.values, columns=df1.columns)
   0  1  2  3  4  5
0  1  2  0  0  0  0
1  2  4  0  0  0  0
2  1  3  0  0  0  0
3  1  3  0  0  0  0

Or if you don't mind overwriting df1:

>>> df1[:] = df1.values * df2.values
>>> df1
   0  1  2  3  4  5
0  1  2  0  0  0  0
1  2  4  0  0  0  0
2  1  3  0  0  0  0
3  1  3  0  0  0  0

Alternatively, You can have some fun with np.broadcast_to, if you want:

>>> df1*np.broadcast_to(df2,df1.shape)
   0  1  2  3  4  5
0  1  2  0  0  0  0
1  2  4  0  0  0  0
2  1  3  0  0  0  0
3  1  3  0  0  0  0
Idell answered 12/10, 2018 at 2:6 Comment(0)
K
1

Using pandas mul

df1.mul(df2.T[0])
Out[22]: 
   1  2  3  4  5  6
0  1  2  0  0  0  0
1  2  4  0  0  0  0
2  1  3  0  0  0  0
3  1  3  0  0  0  0
Kati answered 12/10, 2018 at 2:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.