Convert a pandas DataFrame to GeoJSON (Stations)

In this Python snippet we use stations (geographic) from the Swiss public transportation and convert the data to a GeoJSON (http://geojson.org/) file.

iconv -f ISO-8859-1 -t UTF-8 bfkoordgeo.csv > out.csv

Note: The data is from the Open Data Platform Swiss Public Transport, https://opentransportdata.swiss/en/

Required libraries

Load the data

First let's load the data with pandas. The data frame contains the stations from the public transportations from Switzerland and some from adjoining countries. We have the columns:

  • StationID
  • Longitude
  • Latitude
  • Height
  • Remark

Longitude and Latitude should be WGS 84 coordinates.


In [2]:
import pandas as pd

df = pd.read_csv('data/bfkoordgeo_utf8.csv')
df.head()


Out[2]:
StationID Longitude Latitude Height Remark
0 6.0 7.549783 47.216111 441.0 St. Katharinen
1 7.0 9.733756 46.922368 744.0 Fideris
2 11.0 7.389462 47.191804 467.0 Grenchen Nord
3 16.0 6.513937 46.659019 499.0 La Sarraz, Couronne
4 22.0 7.589551 47.547405 277.0 Basel SBB

Now we do some data cleaning and remove all rows where Longitude and Latitude are 'null'.


In [3]:
df = df[df['Longitude'].notnull()]
df = df[df['Latitude'].notnull()]

# will display all rows that have null values
#df[df.isnull().any(axis=1)]

Convert pandas data frame to GeoJSON

Next we convert the panda data frame to geosjon objects (FeatureCollection/Feature/Point).


In [4]:
import geojson as geojson

values = zip(df['Longitude'], df['Latitude'], df['Remark'])
points = [geojson.Feature(geometry=geojson.Point((v[0], v[1])), properties={'name': v[2]}) for v in values]

geo_collection = geojson.FeatureCollection(points)

print(points[0])


{"geometry": {"coordinates": [7.549783000000001, 47.216111], "type": "Point"}, "properties": {"name": "St. Katharinen"}, "type": "Feature"}

Save the GeoJSON (FeatureCollection) to a file

Finally we dump the GeoJSON objects to a file.


In [5]:
dump = geojson.dumps(geo_collection, sort_keys=True)

'''
with open('stations.geojson', 'w') as file:
    file.write(dump)
'''


Out[5]:
"\nwith open('stations.geojson', 'w') as file:\n    file.write(dump)\n"

Result

You can find the resulat (GeoJSON file) from this snippet here


In [ ]: