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

如何基于两行的相同值合并R语言DataFrame中的行?

合并DataFrame前两行的解决方案

针对你需要合并前两行、保留第一行start和第二行end且其余列保持一致的需求,我们可以用Pandas快速实现:

步骤1:构造示例DataFrame(如果你已经有现成的DataFrame可以跳过这步)

先还原你的数据结构:

import pandas as pd

data = {
    'humcon': [6, 6, 3, 15, 19],
    'seqnames': [6, 6, 3, 15, 19],
    'start': [28179560, 28239933, 52833805, 91426560, 45382034],
    'end': [28239932, 28294888, 52847601, 91426560, 45382034],
    'TAS': ['rs1635', 'rs1635', 'rs3617', 'rs4702', 'rs6859'],
    'Proxy.start': ['rs78270345', 'rs78270345', 'rs3617', 'rs4702', 'rs6859'],
    'Proxy.end': ['rs4711167', 'rs4711167', 'rs2071044', 'rs4702', 'rs6859'],
    'Assembly_NCBI': ['GRCh38.p7']*5
}

df = pd.DataFrame(data)

步骤2:合并前两行

我们直接提取前两行的数据,构造合并后的行,再和剩余行拼接:

# 取出前两行的数据
row1 = df.iloc[0]
row2 = df.iloc[1]

# 复制第一行,将end字段替换为第二行的end值
merged_row = row1.copy()
merged_row['end'] = row2['end']

# 拼接合并行与剩余行,重置索引
new_df = pd.concat([pd.DataFrame([merged_row]), df.iloc[2:]], ignore_index=True)

验证结果

打印new_df就能得到你想要的结果:

humcon  seqnames      start        end     TAS Proxy.start Proxy.end Assembly_NCBI
0       6         6  28179560  28294888  rs1635  rs78270345  rs4711167     GRCh38.p7
1       3         3  52833805  52847601  rs3617       rs3617  rs2071044     GRCh38.p7
2      15        15  91426560  91426560  rs4702       rs4702     rs4702     GRCh38.p7
3      19        19  45382034  45382034  rs6859       rs6859     rs6859     GRCh38.p7

这个方法简单直接,完全匹配你的需求——合并后的行保留了第一行的start、第二行的end,其余列和原两行保持一致。

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:43:14