Python Folium Choropleth Map KeyError: None

2019-07-08 02:07发布

问题:

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