首页 > 解决方案 > 如何使用字符串索引字符串值将 pandas DataFrame 转换为 dict?

问题描述

我有一个带有 2 列的 pandas DataFrame。如何将其转换为具有id键和name值的 Python 字典?

输入

id | name
1  | hello
2  | world

所需输出

{
    "1": "hello",
    "2": "world",
}

标签: pythonpandasdataframedictionary

解决方案


你可以这样做:

In [1256]: df.set_index('id').to_dict()['name']
Out[1256]: {1: 'hello', 2: 'world'}

推荐阅读