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

如何在Pandas中将两列合并为键值对字典列?

问题:将DataFrame两列关联数据合并为字典列

示例数据

skuId   coreAttributes.price    coreAttributes.amount
0   100     price                   8.84
1   102     price                   12.99
2   103     price                   9.99

期望输出

skuId    coreAttributes
100      {'price': 8.84}
102      {'price': 12.99}
103      {'price': 9.99}

尝试的代码及问题

用户尝试了以下代码:

planProducts_T = planProducts.filter(regex = 'coreAttributes').T
planProducts_T.columns = planProducts_T.iloc[0]
planProducts_T.iloc[1:].to_dict(orient = 'records')

收到警告:UserWarning: DataFrame columns are not unique, some columns will be omitted.,且输出结果仅为:

[{'price': 9.99}]

解决方案

方法1:逐行构造字典(直观易用)

直接利用apply逐行生成字典,再保留需要的列:

# 生成coreAttributes字典列
planProducts['coreAttributes'] = planProducts.apply(
    lambda row: {row['coreAttributes.price']: row['coreAttributes.amount']},
    axis=1
)
# 筛选并保留目标列
planProducts = planProducts[['skuId', 'coreAttributes']]

方法2:批量构造字典(高效适用于大数据集)

通过提取列数据,用列表推导式批量生成字典,效率比apply更高:

# 提取键和值的列表
keys = planProducts['coreAttributes.price'].tolist()
values = planProducts['coreAttributes.amount'].tolist()
# 批量生成字典列
planProducts['coreAttributes'] = [{k: v} for k, v in zip(keys, values)]
# 筛选目标列
planProducts = planProducts[['skuId', 'coreAttributes']]

原代码出错原因

原代码转置后将第一行作为列名,但所有列名均为price,导致列名重复。to_dict处理重复列名时只会保留最后一列数据,因此仅输出了最后一行的结果。这种转置思路不适用于当前场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:40:33