Home > front end >  How to change pandas dataframe
How to change pandas dataframe

Time:03-18

I am having a data frame which looks like this

enter image description here

and i want to change it to as shown in the below. How can i change this using pandas

enter image description here

CodePudding user response:

As melt doesn't give the right order here, you have to use stack:

out = df.rename_axis(index='Source', columns='Target').stack() \
        .rename('Weight').reset_index()
print(out)

# Output
  Source Target  Weight
0      A     Fe       2
1      A     Ma      12
2      A   None      50
3     An     Fe       0
4     An     Ma       0
5     An   None       1

Setup MRE:

df = pd.DataFrame({'Fe': {'A': 2, 'An': 0},
                   'Ma': {'A': 12, 'An': 0},
                   'None': {'A': 50, 'An': 1}})
df = df.rename_axis(index='Word', columns='Type')
print(df)

# Output
Type  Fe  Ma  None
Word              
A      2  12    50
An     0   0     1
  • Related