如何将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
相关产品推荐
相关产品推荐

