如何通过映射创建关联Customer ID(行索引+1)与Order ID的DataFrame?
问题描述
我需要创建一个DataFrame,把Customer ID和客户对应的每个Order ID关联起来,其中Customer ID是用行索引+1生成的,想问能不能通过映射来实现?
使用的数据集是invoice_df,包含Order Id、Date、Meal Id等字段,其中Participants字段存储的是参与者姓名的集合。
目前已经实现了以下预处理代码:
import re import pandas as pd # 将字符串形式的参与者集合转换为姓名列表 def string_to_list(participant_string): return re.findall(r"'(.*?)'", participant_string) invoice_df["Participants"] = invoice_df["Participants"].apply(string_to_list) # 获取所有唯一客户姓名数组 customers = invoice_df["Participants"].explode().unique() # 创建新的客户DataFrame customers_df = pd.DataFrame(customers, columns=["CustomerName"]) # 添加customer_id(行索引+1) customers_df["customer_id"] = customers_df.index + 1 # 拆分姓名为名字和姓氏 customers_df["first_name"] = customers_df["CustomerName"].apply(lambda x: x.split(" ")[0]) # 处理多姓氏情况,取空格后的所有部分 customers_df["last_name"] = customers_df["CustomerName"].apply(lambda x: " ".join(x.split(" ")[1:]))
解决方案
完全可以通过映射实现,核心思路是先建立「客户姓名-Customer ID」的映射字典,再将这个映射应用到拆分后的订单-参与者数据上,最终关联Order ID和Customer ID。
具体步骤如下:
- 创建姓名到Customer ID的映射字典
从已有的customers_df中提取映射关系:
name_to_id = customers_df.set_index("CustomerName")["customer_id"].to_dict()
- 拆分订单与参与者的一对多关系
对invoice_df的Participants列进行explode操作,让每个参与者对应一行订单数据:
order_customer = invoice_df.explode("Participants").rename(columns={"Participants": "CustomerName"})
- 通过映射关联Customer ID
使用map方法将客户姓名替换为对应的Customer ID:
order_customer["customer_id"] = order_customer["CustomerName"].map(name_to_id)
- 整理最终结果
保留需要的字段(比如Order Id、customer_id、CustomerName等)即可:
final_df = order_customer[["Order Id", "customer_id", "CustomerName"]].reset_index(drop=True)
这样得到的final_df就实现了Customer ID和每个Order ID的关联,完全通过映射完成,逻辑清晰且高效。
注意:预处理代码里的
first_name拆分存在语法错误(少闭合括号且split(" "[0])是笔误),已经在上面的代码中修正;另外last_name处理多姓氏时,用" ".join(x.split(" ")[1:])比只取[1]更合理,避免遗漏多姓氏的情况。
内容的提问来源于stack exchange,提问作者c200402
相关产品推荐
相关产品推荐

