Home > Enterprise >  How to create dataframe based on matrix?
How to create dataframe based on matrix?

Time:02-23

There are two dataframe I have "df1" and "df2" and one matrix "res"

df1=    a       df2 =   a
        b               c   
        c               e
        d

there are 4 record in df1 and 3 record in df2 so, res = 4*3 matrix

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

so I have above data based on this data or matrix I want following output in the form of dataframe

   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

CodePudding user response:

Set index and columns names by df1, df2:

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

And then reshape by DataFrame.melt:

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

Or DataFrame.stack:

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