Home > Blockchain >  Kronecker product over the rows of a pandas dataframe
Kronecker product over the rows of a pandas dataframe

Time:04-22

So I have these two dataframes and I would like to get a new dataframe which consists of the kronecker product of the rows of the two dataframes. What is the correct way to this?

As an example: DataFrame1

   c1   c2
0  10  100
1  11  110
2  12  120

and DataFrame2

   a1   a2
0  5    7
1  1   10
2  2   4

Then I would like to have the following matrix:

   c1a1   c1a2   c2a1   c2a2
0  50     70     500    700
1  11     110    110    1100
2  24     48     240    480

I hope my question is clear.

PS. I saw this question was posted here kronecker product pandas dataframes. However, the answer given is not the correct answer (I believe to mine and the original question, but definitely not to mine). The answer there gives a Kronecker product of both dataframes, but I only want it over the rows.

CodePudding user response:

Create MultiIndex by MultiIndex.from_product, convert both columns to MultiIndex by DataFrame.reindex and multiple Dataframe, last flatten MultiIndex:

c = pd.MultiIndex.from_product([df1, df2])
df = df1.reindex(c, axis=1, level=0).mul(df2.reindex(c, axis=1, level=1))
df.columns = df.columns.map(lambda x: f'{x[0]}{x[1]}')
print (df)
   c1a1  c1a2  c2a1  c2a2
0    50    70   500   700
1    11   110   110  1100
2    24    48   240   480
  • Related