python - 如何使用字符串索引字符串值将 pandas DataFrame 转换为 dict?
问题描述
我有一个带有 2 列的 pandas DataFrame。如何将其转换为具有id
键和name
值的 Python 字典?
输入
id | name
1 | hello
2 | world
所需输出
{
"1": "hello",
"2": "world",
}
解决方案
你可以这样做:
In [1256]: df.set_index('id').to_dict()['name']
Out[1256]: {1: 'hello', 2: 'world'}
推荐阅读
- c# - 如何组合音频和视频轨道进行播放或从 Web 获取 StorageFile?
- json - 嵌套模板的 JsonToken EndObject 错误
- java - spring data中如何使用自定义数据库方言?
- mysql - 创建等待列表系统并重新排列用户
- c - 当我尝试运行 ncurses 项目时,我的 atom IDE 有什么问题?
- powershell - 在 Powershell 中使用正则表达式时,Leftpad 不起作用
- php - Composer 不在同名目录中自动加载类
- python - 具有多个参数的函数
- python - 从文件中读取行,然后仅将那些不包含特定短语的行写入文件
- php - 如何在浏览器中播放音频文件 (.wav) 而不是下载?