I have this table and I need to melt away this table to be like the expected table where I need to get the point name (a and b) from the column name and let the bq and progress columns melt.
JavaScript
x
5
1
type bq a bq b progress a progress b
2
P 1 1 1 2
3
Q 2 3 4 2
4
R 2 1 1 2
5
The expected result is as below:
JavaScript
1
8
1
type point bq progress
2
P a 1 1
3
P b 1 2
4
Q a 2 4
5
Q b 3 2
6
R a 2 1
7
R b 1 2
8
How can do it in python?
Advertisement
Answer
Try this:
JavaScript
1
6
1
df = pd.DataFrame({'type':['p','q','r'],
2
'bq a':['1','2','2'],
3
'bq b':['1','3','1'],
4
'progress a':['1','4','1'],
5
'progress b':['2','2','2']})
6
JavaScript
1
13
13
1
df_bq = pd.melt(df, id_vars =['type'], value_vars =['bq a','bq b'])
2
df_bq.columns = ['type','point','bq']
3
df_bq['point'] = df_bq['point'].apply(lambda x:x.replace('bq ',''))
4
df_bq.sort_values(by = 'point')
5
6
df_p = pd.melt(df, id_vars =['type'], value_vars =['progress a','progress b'])
7
df_p.columns = ['type','point','progress']
8
df_p['point'] = df_p['point'].apply(lambda x:x.replace('progress ',''))
9
df_p.sort_values(by = 'point')
10
11
df_concat = pd.concat([df_bq, df_p['progress']], axis=1)
12
df_concat
13
Result :