JungleDiff
JungleDiff

Reputation: 3485

Pandas two dataframes multiplication?

I have two data frames (A and B)

A:
column 1, column 2, column 3
0.1        0.5       0.7


B:
row 1          5
row 2          6
row 3          7

how do I perform multiplication to get like

(0.1)*5,  (0.5)* 6,  and (0.7)*7?

In other words, how do I multiply the value in the first row of B with the value in the first column of A, the second row of B with the value in the second column of B, and etc?

Upvotes: 3

Views: 74

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

UPDATE:

In [161]: B
Out[161]:
   col3  col4  col5
0     5     6     7

In [162]: A
Out[162]:
   col1  col2  col3  col4  col5
0   0.1   0.2   0.3   0.4   0.5

In [163]: A[B.columns]
Out[163]:
   col3  col4  col5
0   0.3   0.4   0.5

In [164]: A[B.columns].mul(B.values.ravel())
Out[164]:
   col3  col4  col5
0   1.5   2.4   3.5

UPDATE2:

In [169]: A.loc[:, B.columns] = A[B.columns].mul(B.values.ravel())

In [170]: A
Out[170]:
   col1  col2  col3  col4  col5
0   0.1   0.2   1.5   2.4   3.5

OLD answer:

Not that nice compared to @piRSquared's solution, but it should work:

In [116]: A.T.mul(B.values).T
Out[116]:
   column 1  column 2  column 3
0       0.5       3.0       4.9

or better:

In [123]: A.mul(B.values.ravel())
Out[123]:
   column 1  column 2  column 3
0       0.5       3.0       4.9

Upvotes: 3

piRSquared
piRSquared

Reputation: 294258

you want to multiply their values without respect to whether they are rows or columns.

pd.Series(A.values.ravel() * B.values.ravel())

0    0.5
1    3.0
2    4.9
dtype: float64

Upvotes: 4

Related Questions