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

如何用Python Pandas合并CSV中同用户的多行子余额ID至单行

Pandas实现同组多行转单行多列

针对你需要将同一user_id和user_main_account_id对应的多个user_subbalance_id合并为单行多列的需求,可以用groupby+cumcount+pivot的组合实现,完美避免重复行问题,步骤如下:

步骤说明

  1. 读取CSV数据:用pd.read_csv加载原始文件
  2. 生成组内序号:对每个user_id+user_main_account_id的分组,给每个user_subbalance_id分配唯一序号(从1开始)
  3. 透视转换格式:通过透视表将多行的user_subbalance_id转成单行的多列
  4. 整理结果:重置索引、调整列名格式

完整代码示例

import pandas as pd

# 读取原始CSV(如果CSV字段有多余空格,加skipinitialspace=True自动去除)
df = pd.read_csv('your_file.csv', skipinitialspace=True)

# 给每个分组内的subbalance生成连续序号
df['subbalance_seq'] = df.groupby(['user_id', 'user_main_account_id']).cumcount() + 1

# 透视表转换格式,将多行subbalance转为单行多列
pivoted_df = df.pivot(
    index=['user_id', 'user_main_account_id'],
    columns='subbalance_seq',
    values='user_subbalance_id'
).reset_index()

# 重命名列名,匹配需求的格式
pivoted_df.columns = [
    'user_id', 'user_main_account_id'
] + [f'user_subbalance{i}_id' for i in pivoted_df.columns[2:]]

# 输出结果
print(pivoted_df)

输出结果

运行后会得到你需要的格式:

user_id user_main_account_id user_subbalance1_id user_subbalance2_id
0    abc1                uuid1              toJoin1              toJoin2
1    abc2                uuid2              toJoin3              toJoin4

为什么能避免重复行?

cumcount()会在每个分组内生成唯一的连续序号,确保每个user_subbalance_id对应唯一的列位置,pivot时不会因为重复分组键产生冗余行,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:07:12