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

如何将DataFrame转换为指定格式的字典列表?

将DataFrame转换为指定字典列表的方法

你可以通过两种简洁的方式实现这个转换:

方法一:列表推导式结合iterrows()

直接遍历DataFrame的每一行,将每行的城市名和对应值包装成字典,再存入列表:

# 假设你的DataFrame变量名为df
Cities = [{row["City"]: row["value"]} for _, row in df.iterrows()]

方法二:使用apply()方法

利用apply()对每行数据进行转换,再转为列表:

Cities = df.apply(lambda x: {x["City"]: x["value"]}, axis=1).tolist()

验证输出

运行上述代码后,Cities变量将完全符合你需要的格式:

[{'Paris': 10200000}, {'Beijing': 202000}, {'New York City': 2000}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:00:17