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

如何用Pandas或其他库实现按客户ID拆分可变数据的宽表转换?

我希望使用Pandas处理如下格式的数据:

customer_ids | money spent
---------------------------
00001        | 1000
00001        | 1344
00001        | 1249
00002        | 2345
00003        | 1234
00003        | 1345

即每个客户对应的消费记录("visits")数量不固定,只能通过客户ID的变化判断每个客户的记录数。我希望将数据转换为如下格式:

00001 | 1000 | 1344 | 1249
00002 | 2345
00003 | 1234 | 1345

但我不确定该如何实现,若有除Pandas外的其他库可完成此操作,也请告知。谢谢!

解决方案

使用Pandas实现

通过分组聚合+列展开的方式可以完成转换:

  1. 读取并预处理数据
import pandas as pd

# 读取文本数据,处理分隔符与空格
df = pd.read_csv('your_data.txt', sep='|', skiprows=[1], header=0)
df = df.apply(lambda x: x.str.strip() if x.dtype == 'object' else x)
  1. 按客户ID分组,聚合消费记录为列表
grouped = df.groupby('customer_ids')['money spent'].apply(list).reset_index()
  1. 展开列表为多列并输出目标格式
# 遍历分组结果,拼接成指定格式
for _, row in grouped.iterrows():
    output_parts = [row['customer_ids']] + row['money spent']
    print(' | '.join(output_parts))

使用Python标准库实现(无需第三方依赖)

利用itertools.groupby可以直接完成分组转换:

from itertools import groupby

# 读取并处理数据行
with open('your_data.txt', 'r') as f:
    lines = [line.strip() for line in f if line.strip() and not line.startswith('---')]

# 跳过表头,拆分每条记录为ID和消费金额
data_records = [tuple(part.strip() for part in line.split('|')) for line in lines[1:]]

# 按客户ID分组并输出
for customer_id, group in groupby(data_records, key=lambda x: x[0]):
    amounts = [item[1] for item in group]
    print(' | '.join([customer_id] + amounts))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:32:23