user18425667
user18425667

Reputation:

How to change pandas dataframe

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

Upvotes: 2

Views: 101

Answers (1)

Corralien
Corralien

Reputation: 120391

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

Upvotes: 1

Related Questions