You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中为同一subjectid将base行的led1/led2值复制到followup行

问题解决:将base行的数值复制到同受试者的followup行

输入数据

subjectideventled1led2
ABCD_1234base22.550.3
ABCD_1234followupNANA
ABCD_3456base11.2-23.87
ABCD_3456followupNANA
ZXRT_5555baseNA-0.9
ZXRT_5555followupNANA
EFGH_8976baseNANA
EFGH_8976followupNANA

预期输出

subjectideventled1led2
ABCD_1234base22.550.3
ABCD_1234followup22.550.3
ABCD_3456base11.2-23.87
ABCD_3456followup11.2-23.87
ZXRT_5555baseNA-0.9
ZXRT_5555followupNA-0.9
EFGH_8976baseNANA
EFGH_8976followupNANA

解决方案

方法一:分组填充(简洁高效)

利用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 07:44:58