andrewr
andrewr

Reputation: 815

Python/Pandas convert CSV into dictionary and write to new file

I have a CSV with cluters and their latitude/longitudes like this:

cluster_label,latitude,longitude
0,39.18193382,-77.51885109
1,39.18,-77.27
2,39.17917928,-76.6688633
3,39.1782,-77.2617
4,39.1765,-77.1927

I am trying to convert them into a dictionary using Pandas such as this:

{u'0': [39.18193382,-77.51885109],
 u'1': [39.18,-77.27],
 u'2': [39.17917928,-76.6688633],
 u'3': [39.1782,-77.2617],
 u'4': [39.1765,-77.1927],}

I have converted into a dictionary using .T.to_dict() but when I try to write out to a new file I get Attribute Error(s):'dict' object has no attribute 'to_csv/json/etc.'. How can I convert my csv file to a dictionary and then save the resulting dictionary as a new file?

Code

import pandas as pd

data = pd.read_csv('cluster_centroids.csv', delimiter=',', index_col='cluster_label')

dict = data.T.to_dict()
dict.to_csv('centroidDict.csv')

Upvotes: 0

Views: 1090

Answers (1)

Aklys
Aklys

Reputation: 481

If you are trying to output a dataframe to csv you can do the following rather than convert something to a dictionary.

import pandas as pd

file = 'test.csv'

df = pd.read_csv('test.csv', index_col='cluster_label')

df['co-ords'] = tuple(zip(df.latitude, df.longitude))
df.drop(['latitude', 'longitude'],axis=1, inplace=True)

df.to_csv('centroidDict.csv')

but if you want to just have the dictionary written to a file you may want to take a look at use pickle to retain the information for python to use later.

Upvotes: 1

Related Questions