Search code examples
pythonpandasgeojson

Generate GEOJSON using pandas datframe


I have a pandas dataframe that contains Longitude,Latitude, City, State,Timestamp. I have created one additional column as geometry that is a combination of [Latitude,Longitude].

I wanted to generate a geojson file that contains geomatory information on basis of city something like that https://github.com/adilmoujahid/kaggle-talkingdata-visualization/blob/master/input/geojson/china_provinces_en.json


Solution

  • You can iterate through all rows of the dataframe and build up a dict with the geojson structure. Afterwards, you can dump the dict to a geojson file.

    import json
    
    geojson = {"type": "FeatureCollection", "features": []}
    
    for _, row in df.iterrows():
        feature = {"type": "Feature", "geometry": {"type": "Point", "coordinates": [row['Longitude'], row['Latitude']]}, "properties": {"city": row['city']}}
        geojson['features'].append(feature)
    
    with open('result.geojson', 'w') as fp:
        json.dump(geojson, fp)