我想知道如何将带有值列表的字典映射到数据框

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

我想做这个

City
Seoul
Busan
Deagu
Seoul
Seoul
Busan

现在有 latitudelongtitue

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

我使用下面的代码试过了

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]

但是由于 for loop 没有足够的元素而返回错误 并且需要比迭代列表长度更有效的方法 祝你有美好的一天!

使用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

尝试使用下面的一行代码:

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

或者正如下面提到的@jezrael,您也可以使用以下方式解包:

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

输出:

    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