Plot maps in python error : no arguments in initialization list

127 Views Asked by At

From the following files I want to do a map plot by using folium:

Polygons file: https://drive.google.com/file/d/1uhj7OyHktPseR_CtRD0vPfq8HziHA4RK/view? Postcode variable level: https://drive.google.com/file/d/1oFBITKzqLyTvQEASmZmO6CGCOzdPacgH/view?

Attempt1 (folium):

import pandas as pd
import geopandas as gpd
import folium

df_postcode_variable = pd.read_csv("postcode_sample.csv", dtype=str)  # Postcode variable level
df_postcode_variable['people'] = df_postcode_variable['people'].astype(float)
df_polygons = gpd.read_file("postcode_polygons.shp") # Polygons file
df_polygons.crs = "EPSG:4326"

my_map = folium.Map(location=[41.3890727,2.1572654], zoom_start=13,
                   detect_retina=True, control_scale=False)

folium.Choropleth(
        geo_data=df_polygons,
        name='choropleth',
        data=df_postcode_variable,
        columns=['cp','people'],
        key_on='cp',
        fill_color='OrRd',
        fill_opacity=0.5,
        line_opacity=0.8,
        line_color='Blue',
        legend_name='number of people'
    ).add_to(my_map)

my_map

But I get the following error:

ValueError: key_on `'cp'` not found in GeoJSON.

Attempt 2(pandas_bokeh) working:

import pandas_bokeh
pandas_bokeh.output_notebook()

df_joined=df_polygons.merge(df_postcode_variable.set_index('cp'), on='cp')

df_joined.plot_bokeh(simplify_shapes=20000,
                  category="people", 
                  colormap="Spectral", 
                  hovertool_columns=["cp","people"])

enter image description here

How could I fix this error on folium? cp is in both objects so, It doesnt make sense to me. It seems that is not thetecting cp in df_polygons.

2

There are 2 best solutions below

2
r-beginners On BEST ANSWER

If the geodata is in geopandas format, the key is specified as feature.properties.column_name, as in geojson. See this for details.

my_map = folium.Map(location=[41.3890727,2.1572654], zoom_start=12,
                   detect_retina=True, control_scale=False)

folium.Choropleth(
        geo_data=df_polygons,
        name='choropleth',
        data=df_postcode_variable,
        columns=['cp','people'],
        key_on='feature.properties.cp',
        fill_color='OrRd',
        fill_opacity=0.5,
        line_opacity=0.8,
        line_color='Blue',
        legend_name='number of people'
    ).add_to(my_map)

my_map

enter image description here

1
rvd On

This error message hints at an unexpected data type in your data which is causing np.isnan to complain somewhere under the hood, probably string.

Try changing the data type of your people column to int:

df_postcode_variable['people'] = df_postcode_variable['people'].astype(int)