如何在Python中基于行数据生成新列(Pandas数据框转换)
Pandas DataFrame 宽表转换实现代码
需求说明
现有如下长格式DataFrame:
| ClientId | Product | Quantity |
|---|---|---|
| 01 | Apples | 2 |
| 01 | Oranges | 3 |
| 01 | Bananas | 1 |
| 02 | Apples | 4 |
| 02 | Bananas | 2 |
需要转换为宽格式,其中Product_xxx列为二元变量(客户购买过对应产品则为1,未购买则为0),最终结构如下:
| ClientId | Product_Apples | Quantity_Apples | Product_Oranges | Quantity_Oranges | Product_Bananas | Quantity_Bananas |
|---|---|---|---|---|---|---|
| 01 | 1 | 2 | 1 | 3 | 1 | 1 |
| 02 | 1 | 4 | 0 | 0 | 1 | 2 |
实现代码
import pandas as pd # 构造原始DataFrame(已有数据集可跳过此步) df = pd.DataFrame({ 'ClientId': ['01', '01', '01', '02', '02'], 'Product': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Bananas'], 'Quantity': [2, 3, 1, 4, 2] }) # 添加标识列,用于生成二元变量 df['Product_Flag'] = 1 # 生成透视表,聚合数量和标识值,缺失值补0 pivot_result = df.pivot_table( index='ClientId', columns='Product', values=['Quantity', 'Product_Flag'], fill_value=0, aggfunc='max' ) # 重命名列,调整为目标格式 pivot_result.columns = [f'{col_type}_{product}' for col_type, product in pivot_result.columns] # 重置索引并调整列顺序 final_df = pivot_result.reset_index()[ ['ClientId', 'Product_Apples', 'Quantity_Apples', 'Product_Oranges', 'Quantity_Oranges', 'Product_Bananas', 'Quantity_Bananas'] ] # 查看结果 print(final_df)
代码说明
- 构造原始数据:如果已有现成的DataFrame,直接替换即可,无需重复构造;
- 添加标识列:新增
Product_Flag列固定为1,用于后续生成Product_xxx的二元标识; - 透视表转换:按
ClientId分组,Product作为列维度,分别聚合购买数量(取对应值)和标识(取最大值,确保存在则为1、缺失补0); - 列名调整:将透视表的多级列名重命名为
前缀_产品名的格式; - 列顺序整理:按照需求的列顺序重新排列,得到最终结果。
内容的提问来源于stack exchange,提问作者wlog
相关产品推荐
相关产品推荐

