如何使用pandas将csv转换为字典 [英] how to convert csv to dictionary using pandas

查看:1837
本文介绍了如何使用pandas将csv转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将csv转换为使用pandas的字典?例如,我有2列,并希望column1是关键,column2是值。我的数据如下所示:

 name,position
UCLA,73
SUNY,36

cols = ['name','position']
df = pd.read_csv(filename,names = cols)


解决方案

将列转换为列表,然后压缩并转换为dict: p>

 在[37]:

df = pd.DataFrame({'col1':['first' ,'second','third'],'col2':np.random.rand(3)})
print(df)
dict(zip(list(df.col1),list .col2)))
col1 col2
0第一个0.278247
1秒0.459753
第三个0.151873

[3行x 2列]
Out [37]:
{'third':0.15187291615699894,
'first':0.27824681093923298,
'second':0.4597530377539677}
pre>

How can I convert a csv into a dictionary using pandas? For example I have 2 columns, and would like column1 to be the key and column2 to be the value. My data looks like this:

"name","position"
"UCLA","73"
"SUNY","36"

cols = ['name', 'position']
df = pd.read_csv(filename, names = cols)

解决方案

Convert the columns to a list, then zip and convert to a dict:

In [37]:

df = pd.DataFrame({'col1':['first','second','third'], 'col2':np.random.rand(3)})
print(df)
dict(zip(list(df.col1), list(df.col2)))
     col1      col2
0   first  0.278247
1  second  0.459753
2   third  0.151873

[3 rows x 2 columns]
Out[37]:
{'third': 0.15187291615699894,
 'first': 0.27824681093923298,
 'second': 0.4597530377539677}

这篇关于如何使用pandas将csv转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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