Multiply df rows by df2 rows

Question:

I have two pandas dataframes (both 4004 rows x 24 columns). I want to multiply essentially df1 rows with df2 rows, which I can usually do with df1 * df2

I’ve tried below, but I get nan for all rows

df2 = df2.set_index(df1.index)
df1  = df1 * df2

Also tried below without success. Here I don’t get nan-values but df2 * df2

 df1 = df2.apply(lambda row:row*row,axis = 1)
Asked By: geaa

||

Answers:

You could multiply by .values like this:

import pandas as pd 

data = {
  "col1": [2, 3, 5],
  "col2": [3, 2, 4]
}

df = pd.DataFrame(data)

   col1  col2
0     2     3
1     3     2
2     5     4

data = {
  "col1": [3, 3, 4],
  "col2": [1, 2, 2]
}

df2 = pd.DataFrame(data)

   col1  col2
0     3     1
1     3     2
2     4     2

pd.DataFrame(df.values*df2.values, columns=df.columns, index=df.index)

Output:

   col1  col2
0     6     3
1     9     4
2    20     8
Answered By: Quinten
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.