如何在 Pandas 中将 DataFrame 转换为字典?
pythonserver side programmingprogramming更新于 2025/10/27 20:28:17
要将 Pandas DataFrame 转换为字典,我们可以使用 to_dict() 方法。让我们举个例子,看看它是如何完成的。
步骤
- 创建二维、大小可变、可能异构的表格数据 df。
- 打印输入 DataFrame df。
- 使用 to_dict() 方法将 DataFrame 转换为字典并打印。
示例
import pandas as pd
df = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
print "Input DataFrame is:\n", df
print "Convert DataFrame into dictionary: \n", df.to_dict()
输出
Input DataFrame is:
x y z
0 5 4 9
1 2 7 3
2 7 5 5
3 0 1 1
Convert DataFrame into dictionary:
{'x': {0: 5, 1: 2, 2: 7, 3: 0}, 'y': {0: 4, 1: 7, 2: 5, 3: 1},
'z': {0: 9, 1: 3, 2: 5, 3: 1}}
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

