Home > front end >  Multiply df rows by df2 rows
Multiply df rows by df2 rows

Time:10-02

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)

CodePudding user response:

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
  • Related