Folium Choropleth + GeoJSON вызывает AttributeError: у объекта 'NoneType' нет атрибута 'get' - PullRequest
0 голосов
/ 01 июня 2019

Обнаружил, что кто-то встречал такую ​​же проблему в другом посте ( Folium Choropleth + GeoJSON поднимает AttributeError: 'NoneType' ). Последовал за предложениями там, но моя проблема все еще существует.

Я дважды проверил, что: а) доступ к параметрам правильный б) все доступные ключи в geoJSON содержатся в кадре данных Pandas для Choropleth.

Вот соответствующий блок кода:

import json

# load geojson file into dic
with open('chicago.geojson') as f:
    data = json.load(f)
f.close()

found=0
notfound=0

# check if the features.properties.community data matches the dataframe data 
for feature in data['features']:
    if feature['properties']['community'] in df_cname['COMMUNITY_AREA_NAME'].tolist():
        found=found+1
    else:
        notfound=notfound+1

# print out the check result (and the output shows that all features.properties.community in geojson are found in the dataframe to be used for choropleth drawing.)
print(found,' records found. ', notfound, ' records not found.')   

chicago_geo='chicago.geojson'
latitude = 41.88425
longitude = -87.63245

map_chicago = folium.Map(location=[latitude, longitude], zoom_start=11)

map_chicago.choropleth(
    geo_data=chicago_geo,
    data=df_cname,
    columns=['COMMUNITY_AREA_NAME', 'COUNT'],
    key_on='features.properties.community',
    fill_color='YlOrRd', 
    fill_opacity=0.7, 
    line_opacity=0.2,
    legend_name='Crime Data in Chicago'
)

map_chicago

и вывод / сообщение об ошибке:

77  records found.  0  records not found.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/IPython/core/formatters.py in __call__(self, obj)
    334             method = get_real_method(obj, self.print_method)
    335             if method is not None:
--> 336                 return method()
    337             return None
    338         else:

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/map.py in _repr_html_(self, **kwargs)
    249             self._parent = None
    250         else:
--> 251             out = self._parent._repr_html_(**kwargs)
    252         return out
    253 

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/branca/element.py in _repr_html_(self, **kwargs)
    326 
    327         """
--> 328         html = self.render(**kwargs)
    329         html = "data:text/html;charset=utf-8;base64," + base64.b64encode(html.encode('utf8')).decode('utf8')  # noqa
    330 

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/branca/element.py in render(self, **kwargs)
    319         """Renders the HTML representation of the element."""
    320         for name, child in self._children.items():
--> 321             child.render(**kwargs)
    322         return self._template.render(this=self, kwargs=kwargs)
    323 

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/map.py in render(self, **kwargs)
    336             '</style>'), name='map_style')
    337 
--> 338         super(LegacyMap, self).render(**kwargs)
    339 
    340 

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/branca/element.py in render(self, **kwargs)
    631 
    632         for name, element in self._children.items():
--> 633             element.render(**kwargs)

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/branca/element.py in render(self, **kwargs)
    627         script = self._template.module.__dict__.get('script', None)
    628         if script is not None:
--> 629             figure.script.add_child(Element(script(self, kwargs)),
    630                                     name=self.get_name())
    631 

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/jinja2/runtime.py in __call__(self, *args, **kwargs)
    547                             (self.name, len(self.arguments)))
    548 
--> 549         return self._invoke(arguments, autoescape)
    550 
    551     def _invoke(self, arguments, autoescape):

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/jinja2/runtime.py in _invoke(self, arguments, autoescape)
    551     def _invoke(self, arguments, autoescape):
    552         """This method is being swapped out by the async implementation."""
--> 553         rv = self._func(*arguments)
    554         if autoescape:
    555             rv = Markup(rv)

<template> in macro(l_1_this, l_1_kwargs)

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/jinja2/runtime.py in call(_Context__self, _Context__obj, *args, **kwargs)
    258                 args = (__self.environment,) + args
    259         try:
--> 260             return __obj(*args, **kwargs)
    261         except StopIteration:
    262             return __self.environment.undefined('value was undefined because '

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/features.py in style_data(self)
    563 
    564         for feature in self.data['features']:
--> 565             feature.setdefault('properties', {}).setdefault('style', {}).update(self.style_function(feature))  # noqa
    566             feature.setdefault('properties', {}).setdefault('highlight', {}).update(self.highlight_function(feature))  # noqa
    567         return json.dumps(self.data, sort_keys=True)

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/folium.py in style_function(x)
    303                 'color': line_color,
    304                 'fillOpacity': fill_opacity,
--> 305                 'fillColor': color_scale_fun(x)
    306             }
    307 

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/folium.py in color_scale_fun(x)
    290             def color_scale_fun(x):
    291                 return color_range[len(
--> 292                     [u for u in color_domain if
    293                      get_by_key(x, key_on) in color_data and
    294                      u <= color_data[get_by_key(x, key_on)]])]

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/folium.py in <listcomp>(.0)
    291                 return color_range[len(
    292                     [u for u in color_domain if
--> 293                      get_by_key(x, key_on) in color_data and
    294                      u <= color_data[get_by_key(x, key_on)]])]
    295         else:

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/folium.py in get_by_key(obj, key)
    286                 return (obj.get(key, None) if len(key.split('.')) <= 1 else
    287                         get_by_key(obj.get(key.split('.')[0], None),
--> 288                                    '.'.join(key.split('.')[1:])))
    289 
    290             def color_scale_fun(x):

/opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/folium/folium.py in get_by_key(obj, key)
    285             def get_by_key(obj, key):
    286                 return (obj.get(key, None) if len(key.split('.')) <= 1 else
--> 287                         get_by_key(obj.get(key.split('.')[0], None),
    288                                    '.'.join(key.split('.')[1:])))
    289 

AttributeError: 'NoneType' object has no attribute 'get'

Ваши предложения приветствуются!

...