You need to enable JavaScript to run this app. Python中使用pandas按多条件合并可变数量行的方法
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用pandas按多条件合并可变数量行的方法

问题:基于多条件合并可变数量的行

原始数据集示例

以下为数据集的原始样式示例:

"index" "connector" "type" "q_text" "a_text" "varx" ...
   1        1111      1      aa       NA       xx
   2        9999      2      NA       tt       NA
   3        1111      2      NA       uu       NA
   4        9999      1      bb       NA       yy
   5        9999      1      cc       NA       zz

期望输出结构

期望输出的数据集结构如下:

"index" "connector" "type" "type.1" "q_text" "q_text.1" "a_text" "a_text.1" "varx" "varx.1" ...
   1        1111      1       2        aa        NA        NA        uu        xx      NA
   2        9999      1       2        bb        NA        NA        tt        yy      NA
   3        9999      1       2        cc       NA        NA        tt        zz      NA

合并逻辑

  • 数据集type列取值仅为1或2
  • 同一connector值下,可存在多条type=1的行,但仅存在1条type=2的行

合并规则

  • 当connector取值相同时,将type=2的行与type=1的行合并
  • 由于同一connector下存在多条type=1的行,需将对应的type=2行复制,再与所有同connector的type=1行完成合并

当前存在的问题

现有合并方式无法完成全量合并,核心原因:

  • 多条type=1的行需与唯一对应的type=2行关联
  • 当前场景无法使用SQL实现
    现有尝试的代码逻辑:
df2 = df.copy()
df.index.astype(str)
df2.index.astype(str)
pd.merge(df,df2, how='left', on='connector',right_index=True, left_index=True)
df3 = pd.merge(df.set_index('connector'),df2.set_index('connector'), right_index=True, left_index=True).reset_index()
dfNew = df.merge(df2, how='left', left_on=['connector'], right_on = ['connector'])

核心疑问:能否通过groupby()实现该合并目标?

参考实现方案

来自@victor__von__doom的参考实现代码:

if __name__ == '__main__':
    df = df.groupby('connector', sort=True).apply(lambda c: list(zip(*c.values[:,2:].tolist()))).reset_index(name='merged')
    df[['here', 'are', 'all', 'columns', 'except', 'for', 'the', 'connector', 'column']]  = pd.DataFrame(df.merged.tolist())
    df = df.drop(['merged'], axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 01:15:04