0

How to do element-wise product by column, i am looking for a non-loop technique cause i have dozens of columns in each dataframe and different width size

example:

mat1=pd.DataFrame({"a":[1,1,1],"b":[2,2,2]})
mat2=pd.DataFrame({"c":[1,1,1],"d":[1,2,3]})

output

  ac ad bc bd
0 1  1  2  2
1 1  2  2  4
2 1  3  2  6
Kaoutar
  • 345
  • 2
  • 10

2 Answers2

1

Use DataFrame.mul with MultiIndex.from_product and DataFrame.reindex:

mux = pd.MultiIndex.from_product([mat1.columns, mat2.columns])

df = mat1.reindex(mux,  axis=1, level=0).mul(mat2.reindex(mux,  axis=1, level=1))
df.columns=[f'{a}{b}' for a, b in df.columns]
print (df)
   ac  ad  bc  bd
0   1   1   2   2
1   1   2   2   4
2   1   3   2   6
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

Easy solution

pd.concat((mat2.mul(mat1[c], axis=0).add_prefix(c) for c in mat1), axis=1)

   ac  ad  bc  bd
0   1   1   2   2
1   1   2   2   4
2   1   3   2   6
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53