Search code examples
pythonkeyerrorfoliumchoropleth

Issue with creating choropleth map on Python


I'm trying to create a choropleth map using folium on python and I was able to get the base map running, but when I try to add a layer with neighborhood boundaries, it does not show up on the html page. I thought maybe I had to increase the line opacity, but that doesn't seem to be it.

This is my code:

import folium
    import pandas as pd
    
    crimeData = pd.read_csv('NYC_crime.csv')
    crime2020 = crimeData[crimeData.CMPLNT_FR_DT == 2020]
    
    nycMap = folium.Map(location=[40.693943, -73.985880],zoom_start = 10)
    mapLines = 'nbhdMap.geojson.json'
    
    folium.Choropleth(geo_data = mapLines,
                      data = crime2020,
                      fill_color = 'OrRd',
                      fill_opacity=0.5,
                      line_opacity=1.0,
                      key_on = 'feature.geometry.coordinates',
                      columns = ['Lat_Lon']
                      )
    
    nycMap.save(outfile='index.html')

I'm also having trouble filling the map with data. I'm trying to make it so that each complaint documented on the CSV file from 2020 is used to show which areas received the most calls. But I get this error:

Traceback (most recent call last):
  File "/Users/kenia/Desktop/CSCI233/PRAC.py", line 10, in <module>
    folium.Choropleth(geo_data = mapLines,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/folium/features.py", line 1158, in __init__
    color_data = data.set_index(columns[0])[columns[1]].to_dict()
IndexError: list index out of range

This is the neighborhood boundaries: https://data.beta.nyc/dataset/pediacities-nyc-neighborhoods/resource/35dd04fb-81b3-479b-a074-a27a37888ce7

And this is my data: https://data.cityofnewyork.us/Public-Safety/NYPD-Complaint-Data-Current-Year-To-Date-/5uac-w243


[EDIT] So I tried @r-beginners suggestion with a simpler dataset: https://data.cityofnewyork.us/Health/Restaurants-rolled-up-/59dk-tdhz

import pandas as pd
import folium 

data = pd.read_csv('nycrestaurants.csv')
data = pd.concat([data, str(data['ZIPCODE']).split(',')], axis=1)
data.columns = ['CAMIS', 'DBA', 'BORO', 'BUILDING', 'STREET', 'ZIPCODE']
resData = data.groupby(['ZIPCODE'])['DBA'].sum().reset_index()


nycMap = folium.Map(location=[40.693943, -73.985880],zoom_start = 10)
mapLines = 'zipMap.geojson.json'

folium.Choropleth(geo_data = mapLines,
                  data = resData,
                  key_on = 'feature.properties.postalCode',
                  columns = ['ZIPCODE', 'DBA'],
                  fill_color = 'OrRd',
                  fill_opacity=0.5,
                  line_opacity=1.0
                  ).add_to(nycMap)

nycMap.save(outfile='index.html')

But now I'm getting this error message:

Traceback (most recent call last):
  File "/Users/kenia/Desktop/CSCI233/PRAC.py", line 5, in <module>
    data = pd.concat([data, str(data['ZIPCODE']).split(',')], axis=1)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py", line 274, in concat
    op = _Concatenator(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/reshape/concat.py", line 359, in __init__
    raise TypeError(msg)
TypeError: cannot concatenate object of type '<class 'list'>'; only Series and DataFrame objs are valid

Solution

  • Since you were presented with the data of the complaint in another question, you got the GEOJSON data from here for the corresponding zip code range. As for the process, we have tabulated it by the number of zip codes and tied it to the number of occurrences.

    import pandas as pd
    import numpy as np
    
    df = pd.read_csv('./data/311_Noise_Complaints.csv', sep=',')
    df['Incident Zip'].fillna(0, inplace=True)
    df['Incident Zip'] = df['Incident Zip'].astype(int)
    df_zip = df['Incident Zip'].value_counts().to_frame().reset_index()
    df_zip.columns = ['postal_code', 'counts']
    df_zip['postal_code'] = df_zip['postal_code'].astype(str)
    
    import folium
    
    nycMap = folium.Map(location=[40.693943, -73.985880], zoom_start=10)
    mapLines = './data/nyc_zip_code_tabulation_areas_polygons.geojson'
    
    choropleth = folium.Choropleth(geo_data = mapLines,
                      data = df_zip,
                      columns = ['postal_code', 'counts'],
                      key_on = 'feature.properties.postalcode',
                      fill_color = 'BuPu',
                      fill_opacity=0.5,
                      line_opacity=1.0
                      ).add_to(nycMap)
    
    choropleth.geojson.add_child(
        folium.features.GeoJsonTooltip(['po_name'], labels=False)
    )
    
    nycMap.save(outfile='index.html')
    nycMap
    

    enter image description here