简体   繁体   中英

how to convert csv to dictionary using pandas

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)

Since the 1st line of your sample csv-data is a "header", you may read it as pd.Series using the squeeze keyword of pandas.read_csv() :

>>> pd.read_csv(filename, index_col=0, header=None, 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 ).

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}

ankostis answer in my opinion is the most elegant solution when you have the file on disk.

However, if you do not want to or cannot go the detour of saving and loading from the file system, you can also do it like this:

df = pd.DataFrame({"name": [73, 36], "position" : ["UCLA", "SUNY"]})

series = df["position"]
series.index = df["name"]
series.to_dict()

Result:

{'UCLA': 73, 'SUNY': 36}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM