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

如何将DataFrame中的行转换为指定格式的字典?

将Pandas DataFrame转换为指定格式的字典

假设我有如下的DataFrame:

Column1 | Column2 | Column3
1       |    4    | 23.2
32      |    4.2  | 62.2
9       |    12   | 2.2

我希望得到如下格式的字典:

{
    0: {'Column1':1, 'Column2':4, 'Column3':23.2},
    1: {'Column1': 32, 'Column2':4.2, 'Column3':62.2},
    2: {'Column1':9, 'Column2':12, 'Column3':2.2}
}

实现方法

直接使用Pandas的to_dict()方法,指定参数为'index'就能快速实现:

import pandas as pd

# 构造示例DataFrame
data = {
    'Column1': [1, 32, 9],
    'Column2': [4, 4.2, 12],
    'Column3': [23.2, 62.2, 2.2]
}
df = pd.DataFrame(data)

# 转换为目标格式的字典
result_dict = df.to_dict('index')
print(result_dict)

运行代码后输出的结果会完全匹配你需要的格式。

补充说明

  • to_dict('index')会把DataFrame的行索引作为外层字典的键,每一行的列名与对应值组成内层字典,完美契合需求。
  • 如果你的DataFrame行索引不是默认的连续整数,转换后外层字典的键会对应实际的行索引值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:00:59