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:
如何使用pandas将csv转换为字典?例如,我有2列,并希望column1为键,column2为值。我的数据如下所示:
"name","position"
"UCLA","73"
"SUNY","36"
cols = ['name', 'position']
df = pd.read_csv(filename, names = cols)
2 个解决方案
#1
7
Convert the columns to a list, then zip and convert to a dict:
将列转换为列表,然后压缩并转换为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}
#2
5
More simply you can write:
更简单地说你可以写:
dic = pd.Series.from_csv(filename, names=cols, header=None).to_dict()
#1
7
Convert the columns to a list, then zip and convert to a dict:
将列转换为列表,然后压缩并转换为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}
#2
5
More simply you can write:
更简单地说你可以写:
dic = pd.Series.from_csv(filename, names=cols, header=None).to_dict()