Python:整洁的数据,如何根据需要转换此表?

问题描述

我需要将我的表格从宽格式转换为长表格。该表具有随时间变化的测量值,假设质量随时间变化:m0、m1、m2 等,因此它看起来像这样:

ID | Age | m0 | m1 | m2 | m3
1    67    72   69   66   67
2    70    80   81   79   77
3    72    69   69   70   70

我想要的是:

ID | Age | time | m
1    67     0     72
1    67     1     69
1    67     2     66
1    67     3     67
2    70     0     80
2    70     1     81
2    70     2     79
2    70     3     77
...

感谢您的帮助!提前致谢。

干杯。

解决方法

在这种情况下,您可以使用 pandas melt 方法

result = df.melt(id_vars=['ID','Age'],value_vars=['m0','m1','m2','m3'])
result.columns = ['ID','Age','time','m']
result['time'] = result['time'].str.replace('m','')
result = result.sort_values('Age').reset_index(drop=True)

print(result)
    ID  Age time   m
0    1   67    0  72
1    1   67    1  69
2    1   67    2  66
3    1   67    3  67
4    2   70    0  80
5    2   70    1  81
6    2   70    2  79
7    2   70    3  77
8    3   72    0  69
9    3   72    1  69
10   3   72    2  70
11   3   72    3  70

使用 pd.wide_to_long 的替代方法

result = pd.wide_to_long(df,stubnames=["m"],i=["ID","Age"],j="").reset_index()
result.columns = ['ID','m']
result = result.sort_values('Age').reset_index(drop=True)
print(result)
    ID  Age  time   m
0    1   67     0  72
1    1   67     1  69
2    1   67     2  66
3    1   67     3  67
4    2   70     0  80
5    2   70     1  81
6    2   70     2  79
7    2   70     3  77
8    3   72     0  69
9    3   72     1  69
10   3   72     2  70
11   3   72     3  70

如果像m这样的变量比较多,可以在stubnames里面提一下
pd.wide_to_long 文档:https://pandas.pydata.org/docs/reference/api/pandas.wide_to_long.html