I would like to know how to map dictionary with list of value to dataframe

Viewed 29

I would like to make this

City
Seoul
Busan
Deagu
Seoul
Seoul
Busan

into this which now has latitude and longtitue

City Latitude Logitude
Seoul 127 50
Busan 128 51
Daegu 129 52
Seoul 127 50
Seoul 127 50
Busan 128 51

I tried this using code below

import pandas as pd

dict1 = {"Seoul":[127,50],
         "Busan":[128,51],
         "Daegu":[129,52]}

data = {'City':['Seoul', 'Busan', 'Daegu', 'Seoul','Seoul','Busan']}

test1 = pd.DataFrame(data=data)

for city, list1 in dict1.items():
    print(city," ", list1[0],list1[1])

for num, city, list1 in zip(range(7),dict1.items()):
    if test1.loc[:,"City"] == city:
        test1.loc["Latitude"] = list1[0]
        test1.loc["Longitude"] = list1[1]

But it returned error for not having enough elements for for loop and need more efficient way better than iterating for length of list Have a great day!

2 Answers

Use DataFrame.from_dict with DataFrame.join:

df1 = pd.DataFrame.from_dict(dict1, orient='index', columns=['Latitude','Longitude'])
test1 = test1.join(df1, on='City')
print (test1)
    City  Latitude  Longitude
0  Seoul       127         50
1  Busan       128         51
2  Daegu       129         52
3  Seoul       127         50
4  Seoul       127         50
5  Busan       128         51

Try using the following one-liner:

print(pd.DataFrame([[k] + v for k, v in dict1.items()], columns=['City', 'Latitude', 'Longitude']).set_index('City').loc[data['City']].reset_index())

Or as @jezrael mentioned below, you could also do unpacking with:

print(pd.DataFrame([(k, *v) for k, v in dict1.items()], columns=['City', 'Latitude', 'Longitude']).set_index('City').loc[data['City']].reset_index())

Output:

    City  Latitude  Longitude
0  Seoul       127         50
1  Busan       128         51
2  Daegu       129         52
3  Seoul       127         50
4  Seoul       127         50
5  Busan       128         51
Related