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

将Pandas DataFrame列中的元组列表转换为嵌套字典

问题:将Pandas DataFrame列中的元组列表转为字典格式

现有DataFrame中的列数据为元组列表格式,示例数据如下:

{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}

尝试了一段代码但未成功:

import pandas as pd

df = pd.DataFrame.from_records([{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}])
col_list = ["01AB", "02AB_QTY",]

# for col in col_list:
#     df[col] = df[col].apply(lambda x: {} if x is None else {key: {v[0]:v[1] for v in list_item} for key, list_item in x.items()})

df

期望输出格式:

{'01AB': {"ABC":5,"XYZ":4,"LMN":1}, '02AB_QTY': {"Other":20,"not_Other":150}}

解决方案

你之前的代码错误地对元组列表使用了x.items(),实际上每个列的元素本身就是元组列表,直接用dict()函数就能将其转换为对应的字典结构。

正确代码如下:

import pandas as pd

df = pd.DataFrame.from_records([{'01AB': [("ABC", 5),("XYZ", 4),("LMN", 1)], '02AB_QTY': [("Other", 20),("not_Other", 150)]}])
col_list = ["01AB", "02AB_QTY"]

for col in col_list:
    # 把元组列表转为字典,空列表则返回空字典
    df[col] = df[col].apply(lambda x: dict(x) if x else {})

# 查看转换后的结果
print(df.iloc[0].to_dict())

运行后即可得到你期望的字典格式输出。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 13:30:47