如何将值为列表的字典映射到DataFrame并新增经纬度列
实现代码
方案1:使用map映射后拆分列(最简便,性能最优)
利用pandas的向量化操作,完全不需要写循环遍历:
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) # 映射城市对应经纬度列表 test1['temp'] = test1['City'].map(dict1) # 拆分列表为两列 test1[['Latitude', 'Longitude']] = pd.DataFrame(test1['temp'].tolist(), index=test1.index) # 删除临时列 test1 = test1.drop('temp', axis=1)
运行后即可得到你需要的结构。
方案2:字典转DataFrame后merge(更直观,适合后续拓展维度)
如果后续还要新增城市其他属性,用关联的方式更易维护:
# 把经纬度字典转为城市维度表 geo_df = pd.DataFrame.from_dict(dict1, orient='index', columns=['Latitude', 'Longitude']).reset_index(names='City') # 和原表关联匹配 test1 = test1.merge(geo_df, on='City', how='left')
原代码报错原因
dict1.items()迭代返回的是(城市名, 经纬度列表)二元组,你尝试用num, city, list1三个变量接收,变量数量不匹配直接触发报错range(7)长度远大于字典的3条数据,zip会按照最短的可迭代对象截断,完全无法覆盖原表6行数据if test1.loc[:,"City"] == city返回的是布尔值序列,不能直接作为if的判断条件test1.loc["Latitude"]是对行索引为Latitude的行赋值,不是新增列,逻辑完全错误
内容的提问来源于stack exchange,提问作者이가원
相关产品推荐
相关产品推荐

