如何基于矩阵创建数据框?

How to create dataframe based on matrix?

我有两个数据框“df1”和“df2”以及一个矩阵“res”

df1=    a       df2 =   a
        b               c   
        c               e
        d

df1有4条记录,df2有3条记录 所以, res = 4*3 矩阵

res =
                   df2(index)
                   0    1   2
             0     100  0   0
df1(index)   1     0    0   0
             2     0    100 0
             3     0    0   0

所以我有基于此数据或矩阵的上述数据我想以数据帧的形式输出以下内容

   df1  df2 score
    a   a   100
    a   c   0
    a   e   0
    b   a   0
    b   c   0
    b   e   0
    c   a   0
    c   c   100
    c   e   0
    d   a   0
    d   c   0
    d   e   0

df1, df2设置索引和列名:

res.index = df1[:len(res.index)]
res.columns = df2[:len(res.columns)]

然后通过DataFrame.melt重塑:

df = res.rename_axis(index='df1', columns='df2').melt(ignore_index=False)

DataFrame.stack:

df = res.rename_axis(index='df1', columns='df2').stack().reset_index(name='value')