Python Folium Choropleth映射KeyError:无 [英] Python Folium Choropleth Map KeyError: None

查看:214
本文介绍了Python Folium Choropleth映射KeyError:无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在县级使用Python创建Choropleth地图感兴趣.当我运行代码而不尝试将数据绑定到代码时,我会很漂亮地画出县线.但是,每当我尝试绑定数据时,我都会得到KeyError:无.

I'm interested in creating Choropleth map with Python on a county level. When I run my code without trying to bind data to it I get the county lines drawn in beautifully. However whenever I try to bind my data I get KeyError: None.

从我的搜索看来,这似乎是由于GeoJson中的值与数据文件中的值不匹配...但是我手动输入并检查并已经编辑了数据,因此完全相同行数和完全相同的值...仍然出现相同的错误.非常令人沮丧:(

From my searching it appeared as though this is due to values in the GeoJson not matching up with the values in the data file... but I went in manually and checked and have already edited the data so there are the exact same number of rows and exact same values... still getting the same error. Very frustrating :(

我的代码:

import folium
from folium import plugins
from folium.plugins import Fullscreen
import pandas as pd

county_geo = 'Desktop\counties.json'
county_data = 'Desktop\fips.csv'


# Read into Dataframe, cast to string for consistency.
df = pd.read_csv(county_data, na_values=[' '])
df['FIPS'] = df['FIPS'].astype(str)


m = folium.Map(location=[48, -102], zoom_start=3)

m.choropleth(geo_path=county_geo, 
    data=df,
    columns=['FIPS', 'Value'],
    key_on='feature.properties.id',
    fill_color='PuBu')

Fullscreen().add_to(m)
m

我的错误:

KeyError:无

KeyError: None

出[32]: folium.folium.Map位于0x10231748

Out[32]: folium.folium.Map at 0x10231748

在县一级为您工作的任何建议或示例代码/文件将不胜感激!

Any advice or example code/files that are working for you on a county level would be much appreciated!

我发现了自己的错误.

key_on='feature.properties.id',

应该是:

key_on='feature.id',

推荐答案

import json
keys=[k['id'] for k in json.load(open('Desktop\counties.json')['features']]
missing_keys=set(keys)-set(plot_data['FIPS'])
dicts=[]
for k in missing_keys:
   row={}
   dicts.append({'FIPS': k, 'Value': 0})
dicts
mapdata = country_data
mapdata = mapdata.append(dicts, ignore_index=True)

这将在DataFrame中找到丢失的键并创建值为0的新行. 这可能会解决您的关键错误问题

This will find the missing keys in DataFrame and create new rows with 0 value. This might resolve your key error problem

这篇关于Python Folium Choropleth映射KeyError:无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆