finstats
finstats

Reputation: 1409

Pandas multiply two data frames to get product

I have two data frames with different variable names

df1 = pd.DataFrame({'A':[2,2,3],'B':[5,5,6]})
>>> df1
   A  B
0  2  5
1  2  5
2  3  6
df2 = pd.DataFrame({'C':[3,3,3],'D':[5,5,6]})
>>> df2
   C  D
0  3  5
1  3  5
2  3  6

I want to create a third data frame where the n-th column is the product of the n-th columns in the first two data frames. In the above example, df3 would have two columns X and Y, where df.X = df.A * df.C and df.Y = df.B * df.D

df3 = pd.DataFrame({'X':[6,6,9],'Y':[25,25,36]})
>>> df3
   X   Y
0  6  25
1  6  25
2  9  36

Is there a simple pandas function that allows me to do this?

Upvotes: 2

Views: 5199

Answers (2)

sacuL
sacuL

Reputation: 51335

You can use mul, to multiply df1 by the values of df2:

df3 = df1.mul(df2.values)
df3.columns = ['X','Y']

>>> df3
   X   Y
0  6  25
1  6  25
2  9  36

Upvotes: 6

ArdentLearner
ArdentLearner

Reputation: 732

You can also use numpy as:

df3 = np.multiply(df1, df2)

Note: Most numpy operations will take Pandas Series or DataFrame.

Upvotes: 2

Related Questions