I like to do my data wrangling and analysis work in Python, using the pandas library. I also use Python for much of my data visualization and simple mapping. But for interactive web maps, I usually use Leaflet. There isn’t dead-simple way to dump a pandas DataFrame with geographic data to something you can load with Leaflet. You could use GeoPandas to convert your DataFrame then dump it to GeoJSON, but that isn’t a very lightweight solution.
So, I wrote a simple reusable function to export any pandas DataFrame to GeoJSON:
def df_to_geojson(df, properties, lat='latitude', lon='longitude'): geojson = {'type':'FeatureCollection', 'features':[]} for _, row in df.iterrows(): feature = {'type':'Feature', 'properties':{}, 'geometry':{'type':'Point', 'coordinates':[]}} feature['geometry']['coordinates'] = [row[lon],row[lat]] for prop in properties: feature['properties'][prop] = row[prop] geojson['features'].append(feature) return geojson
You just pass the function a DataFrame, a list of columns to convert to GeoJSON feature properties, and optionally which columns contain the latitude and longitude data. You can use it like this:
cols = ['street_address', 'issue_type', 'status'] geojson = df_to_geojson(df, cols)
And you can easily save it to a .js file for loading into Leaflet, like this:
output_filename = 'dataset.js' with open(output_filename, 'wb') as output_file: output_file.write('var dataset = ') json.dump(geojson, output_file, indent=2)
11 replies on “Exporting Python Data to GeoJSON”
Thank you. No demo necessary. Worked as advertised first attempt!
The link to github repo is not working because the extension “.ipynb” is missing. It should be…
https://github.com/gboeing/urban-data-science/blob/master/17-Leaflet-Web-Mapping/pandas-to-geojson.ipynb
Thanks for the heads-up! Fixed the link.
Actually this doesn’t work for me either.
Link fixed.
thank you, it works well now.
Amazing, thank you !
Hi Geoff,
First of all I want to thank for sharing your expertise, it’s unvaluable.
I’m working with Google Maps API and as backend I’m using Python (Django as my framework). I’ve used your code to transform my data to GeoJson and then trying to use it with Google Maps Data Layers.
When trying to visualize my GeoJson in Google Maps nothing is being shown and after a silly research I’ve noticed that I’m using Lat Lng coords such as [-28, 137] (a place somewhere in Australia)…..however GeoJson coordinates expect coordinates in another specific system in something like this [123.61, -22.14] which is the same place in Australia.
https://developers.google.com/maps/documentation/javascript/datalayer
Do you know what is the GeoJson system for coordinates?
Is it possible to make such transformations in python?
Thanks in advance.
Thanks, it was useful
This is dope. Thanks for posting!
Can the type of coord be polygon?