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

使用Pandas重塑DataFrame:将行值转为列名实现列转行

解决Pandas数据重塑:将Redshift提取表转为用户维度的宽表

我来帮你搞定这个数据转换需求,这类场景属于典型的行转列(宽表转换),需要结合自定义列名和用户维度的聚合,下面是具体实现步骤:

1. 先明确原始数据结构(模拟样例)

假设你从Redshift提取的原始表包含user_id(用户ID)、department(部门)、aisle(货架)、item_cost(商品成本)这几个核心字段,先模拟一份样例数据方便演示:

import pandas as pd

# 模拟Redshift提取的原始数据集
raw_data = pd.DataFrame({
    'user_id': [1001, 1001, 1002, 1002, 1003],
    'department': ['produce', 'dairy', 'produce', 'snacks', 'dairy'],
    'aisle': ['fruits', 'milk', 'vegetables', 'chips', 'cheese'],
    'item_cost': [5.99, 3.49, 4.29, 2.99, 6.79]
})

2. 给每个用户的部门条目添加序号

因为要把同一个用户的多个部门转成department_1、department_2这类列,首先需要给每个用户下的部门按出现顺序编号:

# 按user_id分组,给每个部门条目生成序号(从1开始)
raw_data['dept_seq'] = raw_data.groupby('user_id')['department'].cumcount() + 1

3. 行转列并自定义列名

用pivot方法将多行数据转为单行,同时重命名列名以匹配你的需求:

# 执行 pivot 转换,按user_id分组,按dept_seq拆分列
pivoted_data = raw_data.pivot(
    index='user_id',  # 以user_id作为行索引
    columns='dept_seq',  # 用部门序号作为列的拆分依据
    values=['department', 'aisle', 'item_cost']  # 需要转换的字段
)

# 重命名列:department_1/2,dept_1_aisle/ dept_1_cost等格式
pivoted_data.columns = [
    f'{col[0]}_{col[1]}' if col[0] == 'department' 
    else f'dept_{col[1]}_{col[0]}' 
    for col in pivoted_data.columns
]

# 把user_id从索引变回普通列
pivoted_data = pivoted_data.reset_index()

4. 筛选保留指定的2个用户

最后只保留你需要的2个user_id的行:

# 替换成你实际需要保留的user_id列表
target_users = [1001, 1002]
final_result = pivoted_data[pivoted_data['user_id'].isin(target_users)]

最终效果展示

运行完上述代码后,final_result的结构会是这样:

user_iddepartment_1department_2dept_1_aisledept_2_aisledept_1_item_costdept_2_item_cost
1001producedairyfruitsmilk5.993.49
1002producesnacksvegetableschips4.292.99

完全符合你要求的:每个部门转为department_1/2列,货架和成本对应生成dept_1_aisle、dept_1_item_cost这类列,最终仅保留2行用户数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:25:17