python - 如何将包含每个时间点的列的数据框转换为每个时间点和患者一行的数据框?
问题描述
我有一个结构如下的数据框:
病人 | 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 函数?
解决方案
与一些预处理一起使用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
推荐阅读
- python - Python如何使用strftime自定义日期时间格式
- apache-zookeeper - Patroni (kazoo) 超时但 Zookeeper 集群工作
- javascript - 如何在物化日期选择器中禁用相对于特定日期的过去日期,反之亦然
- sql - Sql server 执行计划不考虑非聚集索引
- javascript - 执行异步函数后执行函数
- r - 如何根据 R 中的其他列将 NA 替换为先前的列值加上一个组?
- r - 是否有一个 R 函数可以绘制一个轴不等间距的图?
- reactjs - 如何清理反应钩子中的承诺数据?
- java - 如何等待一条线完成?
- azure - Azure Web 应用配置无法编辑/删除