首页 > 解决方案 > 如何将包含每个时间点的列的数据框转换为每个时间点和患者一行的数据框?

问题描述

我有一个结构如下的数据框:

病人 day1_temperature day1_blood day2_温度 day2_blood
患者1 37.5°C 120 38℃ 126
病人2 38℃ 129 38℃ 132

每个患者有一行,不同时间点的值都在一行。

但是我想要一个数据框,其中一个患者有几行,每个时间点是一行。它应该有这样的结构:

病人 温度 血压
患者1 1 37.5°C 120
患者1 2 38° 126
病人2 1 38°C 129
病人2 2 38℃ 132

我试图在我的数据帧上使用 melt() ,但它没有导致正确的结果。是否有可用于以所述方式转换数据框的 pandas 函数?

标签: pythonpandas

解决方案


与一些预处理一起使用wide_to_long整数值到列表比较中列名的末尾:

df.columns = [f'{"".join(x[::-1])}' for x in 
              df.columns.str.replace('day','').str.split('_')]
print (df)
    Patient temperature1  blood1 temperature2  blood2
0  Patient1      37.5 °C     120        38 °C     126
1  Patient2        38 °C     129        38 °C     132

df = (pd.wide_to_long(df.reset_index(),
                      stubnames=['temperature','blood'],
                      i=['index','Patient'],
                      j='day')
        .reset_index(level=[1,2])
        .reset_index(drop=True))
print (df)
    Patient  day temperature  blood
0  Patient1    1     37.5 °C    120
1  Patient1    2       38 °C    126
2  Patient2    1       38 °C    129
3  Patient2    2       38 °C    132

推荐阅读