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

如何使用Python实现DataFrame按列分组合并行并动态新增关联列?

Pandas实现分组后多记录横向展开的方法

实现逻辑

核心分3步处理:

  • 补全每个Name对应的File amount值:同Name下该字段仅首行有值、其余为空,按Name分组取组内第一个非空值填充全组,保证同组该字段值唯一
  • 给同组内的other name、other amount记录按出现顺序从1开始编号
  • 对编号后的记录做透视转换,把行数据展开为横向列,最后调整列顺序、空值留空即可

完整可运行代码

import pandas as pd
import numpy as np

# 构造原始示例数据集
df = pd.DataFrame({
    'Name': ['A', 'B', 'C', 'A', 'A', 'B'],
    'File amount': [123, 456, 789, np.nan, np.nan, np.nan],
    'other amount': [48, 48, 49, 48, 48, 48],
    'other name': ['a', 'a', 'a', 'b', 'c', 'd']
})

# 按Name分组填充File amount,保证同组值唯一
df['File amount'] = df.groupby('Name')['File amount'].transform('first')

# 给同组内的other记录按出现顺序生成从1开始的序号
df['n'] = df.groupby('Name').cumcount() + 1

# 分别透视两个other字段
pivot_name = df.pivot(index='Name', columns='n', values='other name')
pivot_amount = df.pivot(index='Name', columns='n', values='other amount')

# 按规则重命名列
pivot_name.columns = [f'other_{i}' for i in pivot_name.columns]
pivot_amount.columns = [f'other_{i} amount' for i in pivot_amount.columns]

# 拼接File amount字段和透视结果,重置索引
res = pd.concat([
    df.groupby('Name')['File amount'].first(),
    pivot_name,
    pivot_amount
], axis=1).reset_index()

# 调整列顺序,保证other_n和对应的other_n amount列相邻
cols = ['Name', 'File amount']
max_n = df['n'].max()
for i in range(1, max_n+1):
    cols.append(f'other_{i}')
    cols.append(f'other_{i} amount')
res = res[cols]

# 如需把空值替换为空字符串,放开下一行注释即可
# res = res.fillna('')

print(res)

运行输出结果

执行代码后得到的结果和预期结构完全一致:

Name  File amount other_1  other_1 amount other_2  other_2 amount other_3  other_3 amount
0    A        123.0       a              48       b            48.0       c            48.0
1    B        456.0       a              48       d            48.0     NaN             NaN
2    C        789.0       a              49     NaN             NaN     NaN             NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:24:31