dvazqgu
dvazqgu

Reputation: 23

How to create a dictionary from a dataframe, being the index the only key?

I have a dataframe called la_crime_refined that looks like the following:

    DR_NO       AREA NAME   LOCATION              LAT       LON
0   10304468    Southwest   1100 W 39TH PL        34.0141   -118.2978
1   190101086   Central     700 S HILL ST         34.0459   -118.2545
2   201418201   Pacific     4700 LA VILLA MARINA  33.9813   -118.4350
3   191501505   N Hollywood 5400 CORTEEN PL       34.1685   -118.4019
4   191921269   Mission     14400 TITUS ST        34.2198   -118.4468

I want to create a dictionary including the Latitudes and longitudes with a unique key: the index. I've tried this:

crime_cord = la_crime_refined[['LAT','LON']].to_dict(orient='index')

However, it returns the key names 'LAT' and 'LON' for every entry on the dictionary.

{0:{'LAT':34.0141,'LON',-118.2978},1:{...}...}

Is there any way to get an output that looks like this:

{0:(34.0141,-118.2978),1:(...)...}

Thank you!

Upvotes: 1

Views: 66

Answers (3)

ctenar
ctenar

Reputation: 808

If you don't mind taking an additional step, you could simply iterate over the dictionary you get back from the to_dict-method:

res = {}
for k, v in la_crime_refined[['LAT','LON']].to_dict(orient='index').items():
    res[k] = (v['LAT'], v['LON'])

Alternatively, you could iterate over the rows of the dataframe (loop or dict-comprehension), e.g.

res = {idx: (row['LAT'], row['LON']) for idx, row in la_crime_refined.iterrows()}

Upvotes: 2

rftr
rftr

Reputation: 1275

Try a dictionary comprehension:

{k: tuple(v.values()) for k, v in crime_cord.items()}

Upvotes: 1

Shamis
Shamis

Reputation: 2604

Since you already have the format in the {'LAT'=X, 'LON'=Y}, the easiest way might be to simply use it as a basis to generate the format you desire:

old_format = {0:{'LAT':34.0141,'LON':-118.2978}, 1:{'LAT':50.0141,'LON':-120.2978}, 2:{'LAT':60,'LON':-130}}
print(old_format)
new_format = {}
for key in old_format.keys():
    new_format[key] = (old_format[key]['LAT'], old_format[key]['LON'])        
print(new_format)

Upvotes: 1

Related Questions