Pandas multiplying two data frames?

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 to 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 B with the value in the first column A, the second row B with the value in the second column B, etc.?

+3


source to share


2 answers


you want to multiply your values ​​without considering 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

      

+4


source


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 so 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

      

+3


source







All Articles