how to convert csv to dictionary using pandas

2020-07-10 07:51发布

问题:

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)

回答1:

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}


回答2:

Since the 1st line of your sample csv-data is a "header", you may read it as pd.Series with this one-liner:

>>> pd.read_csv(filename, index_col=0, squeeze=True).to_dict()
{'UCLA': 73, 'SUNY': 36}

If you want to include also the 1st line, remove the header keyword (or set it to None).