Python GeoJSON – Converting Pandas Column with FeatureCollection to GeoJSON Format

convertfeature-collectiongeojsonpandaspython

I downloaded a CSV that contains a column which has a GeoJSON format and imported it as Pandas DataFrame. How can I convert this to a GeoJSON .geojson? I have about 10,000 rows, each with information as shown below:

This is an example of a cell in the column:

{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-0.0903517,9.488375],[-0.0905786,9.488523],[-0.0909767,9.48913],[-0.09122,9.4895258],[-0.0909733,9.4901503],[-0.0908833,9.4906802],[-0.0906984,9.4905612],[-0.0907146,9.4898184],[-0.090649,9.4895175],[-0.0907516,9.489142],[-0.0906146,9.4889654],[-0.0903517,9.488375]]]},"properties":{"pointCount":"11","length":"502.9413","area":"8043.091133117676"}}]}
Overview of my Pandas DataFrame print now:                             site_registration_gps_area  ...                   geometry
11    {"type":"FeatureCollection","features":[{"type...  ...  POINT (-76.75880 2.38031)
14    {"type":"FeatureCollection","features":[{"type...  ...  POINT (-76.73718 2.33163)
40    {"type":"FeatureCollection","features":[{"type...  ...   POINT (-0.15727 9.69560)
42    {"type":"FeatureCollection","features":[{"type...  ...   POINT (-0.11686 9.65522)
44    {"type":"FeatureCollection","features":[{"type...  ...   POINT (-0.10379 9.65226)

Best Answer

You can use the following code. Just specify json_string_column and output file path.

import json
import pandas as pd
import geopandas as gpd

# df = YOUR DATAFRAME

json_string_column = "site_registration_gps_area" # in df
geojson_out_file = "c:/PATH/TO/file.geojson"

df = df[json_string_column].apply(lambda x: json.loads(x)['features'][0])

gdf = gpd.GeoDataFrame.from_features(df)

with open(geojson_out_file, 'w') as f:
    f.write(gdf.to_json())

The script exports JSON string data contained in json_string_column. If your Pandas DataFrame has other columns, it ignores them.