Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert multiple columns in one column in pandas?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading