【问题标题】:I would like to know how to map dictionary with list of value to dataframe我想知道如何将带有值列表的字典映射到数据框
【发布时间】:2021-10-26 05:38:57
【问题描述】:

我想做这个

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 并且需要比迭代列表长度更有效的方法 祝你有美好的一天!

【问题讨论】:

    标签: python pandas numpy-ndarray


    【解决方案1】:

    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
    

    【讨论】:

    • 好人回答!不得不采用其他解决方案哈哈,其他明智的选择你的。
    • 谢谢你让我知道join!!!看起来我可以在很多情况下使用它。
    【解决方案2】:

    尝试使用以下单行:

    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
    

    【讨论】:

    • print(pd.DataFrame([(k, *v) for k, v in dict1.items()], columns=['City', 'Latitude', 'Longitude']))
    • @jezrael 哦,谢谢你的建议,现在编辑我的答案
    • 感谢您的回答!但是对于[k] 的详细信息,为什么它需要方括号呢?不应该是City 列吗?
    • @이가원 哦,k 是键,它是单个值,例如 Seoul,所以 Seoul + [127, 50] 会出错,所以它必须是 [Seoul] + [127, 50] 才能工作。跨度>
    • 所以为了使用加号运算符,两者都需要是一种列表(或@jezrael建议的指针?
    猜你喜欢
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    • 2018-05-03
    • 2015-07-24
    • 2018-09-21
    • 2018-08-13
    相关资源
    最近更新 更多