Python Forum
How to melt dataframe multiple columns to one column - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to melt dataframe multiple columns to one column (/thread-29861.html)



How to melt dataframe multiple columns to one column - Mekala - Sep-23-2020

Hi,
I have below dataframe, I want to melt all columns to one column. I use below code, but some thing I am missing


import pandas as pd
df = pd.DataFrame({'ID':['A1','A2','A1'],\
'Estart':[1,2,3],\
'Eend':[4,4,5],\
'Rstart':[1,2,1],\
'Rend':[1,6,5]})
pd.melt(df, id_vars=['ID'], value_vars=['Estart','Eend','Rstart','Rend'])
Igot the below outputL
	ID	variable	value
0	A1	Estart	1
1	A2	Estart	4
2	A1	Estart	3
3	A1	Eend	4
4	A2	Eend	4
5	A1	Eend	5
6	A1	Rstart	1
7	A2	Rstart	2
8	A1	Rstart	1
9	A1	Rend	1
10	A2	Rend	6
11	A1	Rend	5
I want as below: Some help how to arrange ad below:


ID	variable	value
A1	Estart	1
A1	Eend	4
A1	Rstart	1
A1	Rend	1
A2	Estart	2
A2	Eend	4
A2	Rstart	2
A2	Rend	6
A1	Estart	3
A1	Eend	5
A1	Rstart	1
A1	Rend	5



RE: How to melt dataframe multiple columns to one column - scidam - Sep-24-2020

There is .sort_values method which can help you to get desired order; Take a look at
the following example:
import numpy as np

@np.vectorize
def key_func(x):
    # This function impacts on sorting logic;
    if x.endswith('end'):
        return x[0] + '2'
    elif x.endswith('start'):
        return x[0] + '1'
    return x

pd.melt(df, id_vars=['ID'], value_vars=['Estart','Eend','Rstart','Rend']).sort_values(['ID', 'variable'], key=key_func)
So, you need to change key_func to meet your needs (however, I didn't understand the sorting logic lies behind the order that you want to get).