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

如何根据Pandas DataFrame某列值将另外两列生成对应字典?

Pandas按列分组生成对应字典的解决方法

原始数据

import pandas as pd
df = pd.DataFrame({
    'a': ['brand', 'brand', 'seat', 'seat'],
    'b': ['F', 'G', 'yes', 'no'],
    'c': [0, 1, 1, 0]
})

预期输出

得到两个字典:

brand = {'F':0,'G':1}
seat = {'no':0,'yes':1}

错误尝试代码

dic = {}
for x,y in zip(b.values, c.values):
    dic.setdefault(y,[]).append(x)

可行方案

方案1:遍历分组构建字典

# 初始化结果容器
result_dict = {}
# 按列a分组,遍历每个分组
for group_name, sub_df in df.groupby('a'):
    # 将当前分组的b列作为键,c列作为值构建字典
    result_dict[group_name] = dict(zip(sub_df['b'], sub_df['c']))

# 提取目标字典
brand = result_dict['brand']
seat = result_dict['seat']

方案2:用agg聚合简化代码

# 分组后直接聚合生成字典,再转为最终的嵌套字典
result_dict = df.groupby('a').apply(lambda group: dict(zip(group['b'], group['c']))).to_dict()

brand = result_dict['brand']
seat = result_dict['seat']

两种方案都能实现需求,将列a的每个唯一值作为外层键,对应行的b和c分别作为内层字典的键和值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:53:13