Python Folium Choropleth Map KeyError: None

馋奶兔 提交于 2020-01-04 05:29:09

问题


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.

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

My code:

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

And my error:

KeyError: None

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!

EDIT:

I found my own error.

key_on='feature.properties.id',

Should be:

key_on='feature.id',

回答1:


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)

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



来源:https://stackoverflow.com/questions/38014480/python-folium-choropleth-map-keyerror-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!