0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I would like to retain the dictionary structure in a new file. The purpose is to then read this dictionary file as a positions in a networkx graph as mentioned in the 2nd answer here: stackoverflow.com/questions/19915266/…
Well there is a number of options for writing the dictionary to a file. You can pickle it if you don't need it to be human readable when stored. You could us JSON or XML to store it as readable. You can always keep the data in the DataFrame above and convert it at the time you need to. But it looks like NetworkX may be able to take information from a DataFrame as well so I'd potentially look at doing that. But I'm not familiar with NetworkX so unsure in that regards.
Okay, thanks for your help. I attempted to just convert to a dict and have NetworkX read the dict within the script instead of another file but ran into errors there as well. I'll have to tinker some and ask more questions on the topic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.