How to combine 2 dataframes, using the dot product

Viewed 60

I have 2 dataframes:

df_1 = pd.DataFrame({"c1":[2,3,5,0], 
                     "c2":[1,0,5,2], 
                     "c3":[8,1,5,1]}, 
                     index=[1,2,3,4])

df_2 = pd.DataFrame({"u1":[1,0,1,0], 
                     "u2":[-1,0,1,1]}, 
                     index=[1,2,3,4])

For every combination of "c" and "u", I want to calculate the dot product, e.g. with np.dot().

For example, the value of c1-u1 is calculated like this: 2*1 + 3*0 + 5*1 + 0*0 = 7

The resulting dataframe should look like this:

     u1   u2
c1   7    3
c2   6    6
c3   13   -2

Is there an "elegant" way of solving this or is iterating through the 2 dataframes the only way?

2 Answers

Do you mean:

df_1.T @ df_2
# or equivalently
# df1.T.dot(df2)

Output:

    u1  u2
c1   7   3
c2   6   6
c3  13  -2

We can do matrix multiplication using pandas dot function.

df_1.T.dot(df_2)

Output:

    u1  u2
c1  7   3
c2  6   6
c3  13  -2
Related