python pandas数据框到字典 [英] python pandas dataframe to dictionary

查看:54
本文介绍了python pandas数据框到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个两列数据框,并打算将其转换为 python 字典 - 第一列将是键,第二列将是值.先感谢您.

I've a two columns dataframe, and intend to convert it to python dictionary - the first column will be the key and the second will be the value. Thank you in advance.

数据框:

    id    value
0    0     10.2
1    1      5.7
2    2      7.4

推荐答案

请参阅 to_dict.你可以这样使用它:

See the docs for to_dict. You can use it like this:

df.set_index('id').to_dict()

如果你只有一列,为了避免列名也是字典中的一个级别(实际上,在这种情况下,你使用了Series.to_dict()):

And if you have only one column, to avoid the column name is also a level in the dict (actually, in this case you use the Series.to_dict()):

df.set_index('id')['value'].to_dict()

这篇关于python pandas数据框到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆