pythonjsonfoliumchoropleth

json in Python - str to int


I am trying to learn how to create Geographical Visualizations with Python. I have downloaded json of UK cities. But they are coming in as str and so I don't know how to use them.

My json is from here: https://simplemaps.com/data/gb-cities

My code is:

# Setup a folium map at a high-level zoom
venue_map = folium.Map(location = [20,78], zoom_start = 2.5)

# Choropleth maps bind Pandas Data Frames and json geometries.This allows us to quickly visualize data combinations
folium.Choropleth(
    geo_data = country_geo, 
    data = data_to_plot1,
    columns = ["city", "xg"],
    key_on = 'feature.CopyPasteDiv',
    fill_color = 'YlOrBr', fill_opacity=0.6, line_opacity=0.1,
    legend_name = "Expected Goals per city").add_to(venue_map)
folium.LayerControl().add_to(venue_map)

venue_map

I am also wondering if my key_on is correct.


Solution

  • If I download the gb.json files from that site, I get a file that is a list of json dictionaries like:

    [
      {
        "city": "London", 
        "lat": "51.5072", 
        "lng": "-0.1275", 
        "country": "United Kingdom", 
        "iso2": "GB", 
        "admin_name": "London, City of", 
        "capital": "primary", 
        "population": "11262000", 
        "population_proper": "8825001"
      }
    ]
    

    I assume that the issue you are running into has something to do with "population" being a string rather than a number. As a secondary issue, I don't see an attribute "xg" in these items so maybe you want a different one.

    To recast the population numbers to integers, you can do:

    import json
    with open("gb.json", "r") as file_in:
        rows = json.load(file_in)
        for row in rows:
            row["population"] = int(row["population"])
    print(rows)
    

    Then try passing rows to folium.Choropleth()