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

如何用Pandas将DataFrame转换为{Plant Delivering ID: [Ship-To ID]}格式的字典?

Pandas将DataFrame转换为Plant对应多Ship-To ID的字典

假设你的DataFrame包含Plant Delivering ID和Ship-To ID两列,要实现单个Plant对应多个Ship-To ID的列表字典,可通过以下步骤完成:

核心思路

按Plant Delivering ID分组,将每组的Ship-To ID聚合为列表,再转换为字典格式。

代码实现

1. 构造示例数据(模拟你的原始DataFrame)

import pandas as pd

# 模拟原始数据
data = {
    'Plant Delivering ID': ['P001', 'P001', 'P002', 'P002', 'P002', 'P003'],
    'Ship-To ID': ['S001', 'S002', 'S003', 'S004', 'S003', 'S005']
}
df = pd.DataFrame(data)

2. 转换为目标字典

保留重复的Ship-To ID

如果不需要去重,直接分组聚合:

# 分组后将Ship-To ID转为列表,再转字典
plant_ship_dict = df.groupby('Plant Delivering ID')['Ship-To ID'].agg(list).to_dict()

输出结果:

{'P001': ['S001', 'S002'], 'P002': ['S003', 'S004', 'S003'], 'P003': ['S005']}

去重并保持顺序

如果同一个Plant下的Ship-To ID有重复,且需要去重:

# 先去重,再分组聚合
plant_ship_dict_unique = df.drop_duplicates(subset=['Plant Delivering ID', 'Ship-To ID'])\
                          .groupby('Plant Delivering ID')['Ship-To ID'].agg(list).to_dict()

输出结果:

{'P001': ['S001', 'S002'], 'P002': ['S003', 'S004'], 'P003': ['S005']}

代码解释

  • groupby('Plant Delivering ID'):按配送工厂ID对数据分组
  • ['Ship-To ID'].agg(list):将每组内的所有Ship-To ID合并为一个列表
  • .to_dict():将分组后的Series直接转换为{Plant: [Ship-To列表]}的字典格式
  • drop_duplicates(subset=...):指定去重的列组合,确保同一个Plant下的Ship-To ID唯一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:05:20