Python脚本实现指定列值转置为多列的技术需求
客户联系人数据转置解决方案
问题描述
现有如下结构的DataFrame:
| customer_id | customer_location | customer_contact_id | customer_contact_location |
|---|---|---|---|
| 1 | ES | 10 | DE |
| 1 | ES | 11 | DE |
| 1 | ES | 12 | FR |
| 2 | FR | 20 | GB |
| 3 | ES | 87 | ES |
| 3 | ES | 88 | ES |
需要将其转换为每个customer_id对应一行的格式,输出列包括:customer_id、customer_location、customer_contact_id1、customer_contact_id2、customer_contact_id3、customer_contact_location1、customer_contact_location2、customer_contact_location3,最终输出数据如下:
| customer_id | customer_location | customer_contact_id1 | customer_contact_id2 | customer_contact_id3 | customer_contact_location1 | customer_contact_location2 | customer_contact_location3 |
|---|---|---|---|---|---|---|---|
| 1 | ES | 10 | 11 | 12 | DE | DE | FR |
| 2 | FR | 20 | GB | ||||
| 3 | ES | 87 | 88 | ES | ES |
同时脚本需满足以下要求:
- 以输入DataFrame为处理对象
- 转置联系人层级数据,实现单customer_id对应单行
- 以全量数据中单个customer_id对应的联系人最大数量,作为每个联系人属性的列数(示例中最大值为3,故各生成3列)
- 支持动态配置:可自定义无需转置的客户层级列和需要转置的联系人层级列,便于后续扩展属性
实现代码
import pandas as pd # 构造示例输入DataFrame data = [ [1, "ES", 10, "DE"], [1, "ES", 11, "DE"], [1, "ES", 12, "FR"], [2, "FR", 20, "GB"], [3, "ES", 87, "ES"], [3, "ES", 88, "ES"] ] df = pd.DataFrame(data, columns=["customer_id", "customer_location", "customer_contact_id", "customer_contact_location"]) # 动态配置项 # 客户层级列:无需转置的列 customer_cols = ['customer_id', 'customer_location'] # 联系人层级列:需要转置的列 contact_cols = ['customer_contact_id', 'customer_contact_location'] # 计算单个客户对应的最大联系人数量 max_contact_count = df.groupby('customer_id').size().max() # 为每个客户的联系人添加序号 df['contact_seq'] = df.groupby('customer_id').cumcount() + 1 # 拆分客户层级和联系人层级数据,分别处理 customer_df = df[customer_cols].drop_duplicates() contact_df = df[customer_cols + contact_cols + ['contact_seq']] # 对联系人数据进行透视,生成带序号的列 pivoted_contact = contact_df.pivot( index=customer_cols, columns='contact_seq', values=contact_cols ) # 重命名列,格式为"原列名+序号" pivoted_contact.columns = [f"{col[0]}{col[1]}" for col in pivoted_contact.columns] # 合并客户层级数据和透视后的联系人数据 result_df = customer_df.merge(pivoted_contact, on=customer_cols, how='left') # 按指定列顺序排序(可选,保证列顺序符合预期) sorted_columns = customer_cols + [f"{col}{i}" for col in contact_cols for i in range(1, max_contact_count+1)] result_df = result_df[sorted_columns] # 打印结果(空值替换为空字符串) print(result_df.fillna('').to_csv(sep=',', index=False))
配置说明
customer_cols:定义无需转置的客户核心属性列,新增客户属性时直接添加到列表即可contact_cols:定义需要按联系人序号转置的属性列,新增联系人属性时直接添加到列表即可max_contact_count:自动计算全量数据中单个客户的最多联系人数量,动态生成对应数量的转置列
内容的提问来源于stack exchange,提问作者Kristina
相关产品推荐
相关产品推荐

