在R语言中为同一subjectid将base行的led1/led2值复制到followup行
问题解决:将base行的数值复制到同受试者的followup行
输入数据
| subjectid | event | led1 | led2 |
|---|---|---|---|
| ABCD_1234 | base | 22.5 | 50.3 |
| ABCD_1234 | followup | NA | NA |
| ABCD_3456 | base | 11.2 | -23.87 |
| ABCD_3456 | followup | NA | NA |
| ZXRT_5555 | base | NA | -0.9 |
| ZXRT_5555 | followup | NA | NA |
| EFGH_8976 | base | NA | NA |
| EFGH_8976 | followup | NA | NA |
预期输出
| subjectid | event | led1 | led2 |
|---|---|---|---|
| ABCD_1234 | base | 22.5 | 50.3 |
| ABCD_1234 | followup | 22.5 | 50.3 |
| ABCD_3456 | base | 11.2 | -23.87 |
| ABCD_3456 | followup | 11.2 | -23.87 |
| ZXRT_5555 | base | NA | -0.9 |
| ZXRT_5555 | followup | NA | -0.9 |
| EFGH_8976 | base | NA | NA |
| EFGH_8976 | followup | NA | NA |
解决方案
方法一:分组填充(简洁高效)
利用groupby按受试者分组,结合transform填充分组内的非缺失值:
import pandas as pd # 构造输入数据框 df = pd.DataFrame({ 'subjectid': ['ABCD_1234', 'ABCD_1234', 'ABCD_3456', 'ABCD_3456', 'ZXRT_5555', 'ZXRT_5555', 'EFGH_8976', 'EFGH_8976'], 'event': ['base', 'followup', 'base', 'followup', 'base', 'followup', 'base', 'followup'], 'led1': [22.5, None, 11.2, None, None, None, None, None], 'led2': [50.3, None, -23.87, None, -0.9, None, None, None] }) # 对led1、led2列按subjectid分组填充 df[['led1', 'led2']] = df.groupby('subjectid')[['led1', 'led2']].transform( lambda x: x.fillna(x.dropna().iloc[0] if not x.dropna().empty else x) )
说明:
groupby('subjectid')将数据按受试者分组,确保每个组内是同一受试者的base和followup行transform保证返回结果与原数据行数一致,不会改变原有结构- 匿名函数中,先过滤分组内的非缺失值,用第一个有效值(即base行的值)填充该组的缺失值;如果分组内全为NA,则保持原样
方法二:合并填充(逻辑直观)
先提取base行的有效数据,再合并回原数据框完成填充:
import pandas as pd # 构造输入数据框 df = pd.DataFrame({ 'subjectid': ['ABCD_1234', 'ABCD_1234', 'ABCD_3456', 'ABCD_3456', 'ZXRT_5555', 'ZXRT_5555', 'EFGH_8976', 'EFGH_8976'], 'event': ['base', 'followup', 'base', 'followup', 'base', 'followup', 'base', 'followup'], 'led1': [22.5, None, 11.2, None, None, None, None, None], 'led2': [50.3, None, -23.87, None, -0.9, None, None, None] }) # 提取base行的subjectid和对应led值 base_data = df[df['event'] == 'base'][['subjectid', 'led1', 'led2']] # 合并数据,用base值填充followup的缺失值 df = df.merge(base_data, on='subjectid', suffixes=('', '_base'), how='left') df['led1'] = df['led1'].fillna(df['led1_base']) df['led2'] = df['led2'].fillna(df['led2_base']) # 删除临时生成的合并列 df = df.drop(['led1_base', 'led2_base'], axis=1)
说明:
- 先筛选出
event='base'的行,保留关键列 - 通过
left join将base行的数据匹配到对应受试者的所有行 - 用
fillna将原列的缺失值替换为base行的数值,最后清理临时列
内容的提问来源于stack exchange,提问作者user123
相关产品推荐
相关产品推荐

