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

R语言:如何根据指定列取值将一行拆分为多行?

问题:展开DataFrame的多参与者列到单行记录

原始DataFrame结构如下:

ID Date Participant_1 Participant_2 Participant_3 Covariate 1 Covariate 2 Covariate 3
1 9/1      A             B                            16           2           1
2 5/4      B                                          4            2           2
3 6/3      C             A              B             8            3           6
4 2/8      A                                          7            8           4
5 9/3      C             A                            7            1           3

需求:将该DataFrame展开,使每个事件ID对应的所有参与者各占一行,保留日期及协变量值,合并多参与者列为单个Participant列,最终得到如下格式:

ID Date Participant  Covariate 1 Covariate 2 Covariate 3
1 9/1      A               16           2           1
1 9/1      B               16           2           1
2 5/4      B               4            2           2
3 6/3      C               8            3           6
3 6/3      A               8            3           6
3 6/3      B               8            3           6
4 2/8      A               7            8           4
5 9/3      C               7            1           3
5 9/3      A               7            1           3

高效实现方法:使用pandas的melt函数

这是典型的宽表转长表场景,melt函数比pivot更适配这种需求。以下是完整实现代码:

import pandas as pd

# 构造原始DataFrame(实际场景中可替换为读取文件逻辑)
df = pd.DataFrame({
    'ID': [1, 2, 3, 4, 5],
    'Date': ['9/1', '5/4', '6/3', '2/8', '9/3'],
    'Participant_1': ['A', 'B', 'C', 'A', 'C'],
    'Participant_2': ['B', None, 'A', None, 'A'],
    'Participant_3': [None, None, 'B', None, None],
    'Covariate 1': [16, 4, 8, 7, 7],
    'Covariate 2': [2, 2, 3, 8, 1],
    'Covariate 3': [1, 2, 6, 4, 3]
})

# 执行宽表转长表操作
melted_df = df.melt(
    # 指定需要保留的核心列(这些列会随参与者行重复)
    id_vars=['ID', 'Date', 'Covariate 1', 'Covariate 2', 'Covariate 3'],
    # 指定需要展开的参与者列
    value_vars=['Participant_1', 'Participant_2', 'Participant_3'],
    # 设置展开后的参与者列名称
    value_name='Participant'
)

# 过滤空参与者记录,清理冗余列并排序
result_df = melted_df.dropna(subset=['Participant']) \
                     .drop(columns='variable') \
                     .sort_values('ID') \
                     .reset_index(drop=True)

# 输出结果
print(result_df)

关键参数说明:

  • id_vars:定义转换过程中保持不变的列,即需要重复保留的ID、日期和协变量列
  • value_vars:指定需要被"拉长"的列,也就是所有参与者相关的列
  • value_name:设置转换后存储参与者值的新列名称

执行后即可得到符合需求的DataFrame,该方法处理效率高,适合大规模数据场景。

内容的提问来源于stack exchange,提问作者flâneur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:25:19