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
CodePudding user response:
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
CodePudding user response:
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