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

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

问题描述

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



数据框:

  id值
0 0 10.2
1 1 5.7
2 2 7.4


解决方案

请参阅 的文档to_dict 。你可以这样使用:

  df.set_index('id')to_dict()

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

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


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.

Dataframe:

    id    value
0    0     10.2
1    1      5.7
2    2      7.4

解决方案

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

df.set_index('id').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天全站免登陆