简体   繁体   English

我想知道如何将 map 字典的值列表设为 dataframe

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

I would like to make this我想做这个

City城市
Seoul汉城
Busan釜山
Deagu德古
Seoul汉城
Seoul汉城
Busan釜山

into this which now has latitude and longtitue进入现在具有latitudelongtitue的这个

City城市 Latitude纬度 Logitude逻辑
Seoul汉城 127 127 50 50
Busan釜山 128 128 51 51
Daegu大邱 129 129 52 52
Seoul汉城 127 127 50 50
Seoul汉城 127 127 50 50
Busan釜山 128 128 51 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!但它返回错误,因为没有足够的for loop元素,需要比迭代列表长度更有效的方法祝你有美好的一天!

Use DataFrame.from_dict with DataFrame.join :使用DataFrame.from_dictDataFrame.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:或者正如下面提到的@jezrael,您也可以使用以下方式进行解包:

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

Output: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM