Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 988
DevEx Avatar asked Apr 14 '14 10:04

DevEx


2 Answers

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).

like image 104
ankostis Avatar answered Oct 15 '22 19:10

ankostis


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}
like image 39
PeterHeuz Avatar answered Oct 15 '22 21:10

PeterHeuz