-1

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)
geaa
  • 59
  • 6
  • Have you tried removing `df2 = df2.set_index(df1.index)` and doing `df1 = df1 * df2` directly? – Stef Oct 01 '22 at 12:31
  • I can't reproduce your issue. `df1 = df1 * df2` works great for me. Could you give an example of dataframes where that doesn't work? – Stef Oct 01 '22 at 12:32
  • Please read [How to make good reproducible pandas examples?](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) for help with providing an example. – Stef Oct 01 '22 at 12:34
  • That probably means your dataframes have incompatible sizes, and not _(both 4004 rows x 24 columns)_ as you said. – AboAmmar Oct 01 '22 at 12:41
  • 1
    same sizes of dataframes. ".values" did it as per answer below – geaa Oct 01 '22 at 13:01

1 Answers1

0

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
Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Is there any point in using `.values`? With your example I can do `result = df * df2` directly and it appears to work fine. – Stef Oct 01 '22 at 12:32