如何从列名中获取字符串并在 python 中熔化多个列?

How to get a string from column names and melt multiple columns in python?

我有这个 table 我需要把这个 table 融化成像预期的 table 我需要从中获取点名称(a 和 b)列名称并让 bq 和进度列融化。

type    bq a    bq b    progress a    progress b
P        1       1          1             2
Q        2       3          4             2
R        2       1          1             2

预期结果如下:

type     point      bq    progress
P         a         1        1
P         b         1        2
Q         a         2        4
Q         b         3        2
R         a         2        1
R         b         1        2

如何在python中做到?

试试这个:

df = pd.DataFrame({'type':['p','q','r'],
                  'bq a':['1','2','2'],
                  'bq b':['1','3','1'],
                  'progress a':['1','4','1'],
                  'progress b':['2','2','2']})

df_bq = pd.melt(df, id_vars =['type'], value_vars =['bq a','bq b'])
df_bq.columns = ['type','point','bq']
df_bq['point'] = df_bq['point'].apply(lambda x:x.replace('bq ',''))
df_bq.sort_values(by = 'point')

df_p = pd.melt(df, id_vars =['type'], value_vars =['progress a','progress b'])
df_p.columns = ['type','point','progress']
df_p['point'] = df_p['point'].apply(lambda x:x.replace('progress ',''))
df_p.sort_values(by = 'point')

df_concat = pd.concat([df_bq, df_p['progress']], axis=1)
df_concat

结果: