Create Dictionary with Panda Dataframe

Viewed 54

I have a dataframe which is called "df" as follows.

enter image description here

My goal is to create a dictionary. The key is gonna be poiid and values are gonna be lng and lat for dictionary.

Example dictionary output

{0: (30.2359091167, -97.7951395833),
 1: (30.2691029532, -97.7493953705),
 2: (30.2557309927, -97.7633857727),
 3: (30.2634181234, -97.7575966669),
 4: (30.2742918584, -97.7405226231),
 5: (30.261599404, -97.7585805953),
...

My solution;

dictionary = df.groupby('poiid')['lng'].agg(set).to_dict()

my solution works but I couldn't add the 'lat' column into the dictionary.

I am open to see other solutions

2 Answers

First set your index as poiid so that when you want to create a dictionary, key would be poiid. Then get the columns you want and make them tuple. In the last step, you create a dictionary out of it.

df = df.set_index('poiid')[['lng', 'lat']].apply(tuple, axis=1).to_dict()

You should set poiid as index with df = df.set_index("poiid") then use df.to_dict("index")

Related