I have the following dataframe:
route1 route2
1 19.0 51.0
2 47.0 46.0
3 56.0 37.0
4 43.0 2.0
I would like to have the following output.
edge route
1 19.0 route1
2 47.0 route1
3 56.0 route1
4 43.0 route1
5 51.0 route2
6 46.0 route2
7 37.0 route2
8 2.0 route2
How can I do that? I checked that Pandas: Multiple columns into one column but it doesnt help that much with the new column routes that I want to create.
Thank you in advance!
>Solution :
Use melt:
>>> df.melt(var_name='route', value_name='edge')
route edge
0 route1 19.0
1 route1 47.0
2 route1 56.0
3 route1 43.0
4 route2 51.0
5 route2 46.0
6 route2 37.0
7 route2 2.0
If you have some columns to protect, use id_vars=['col1', 'col2', ...] to not flatten them.