Merge two GeoJSON into one in a dataframe

Viewed 51

I have a dataframe containing GeoJSON:

data = {'geojson': {0: '{"type":"LineString","coordinates":[[1,4],[2,5]]}',
      1: '{"type":"LineString","coordinates":[[3,6],[4,7]]}'},
     'checkpoint': {0: 6, 1: 0},'lom_name': {0: 'marathon19', 1: 'marathon19'}}
df = pd.DataFrame.from_dict(data)

enter image description here

The desired result is:

   geojson                                                             lob_name
    {"type":"LineString","coordinates":[[1,4],[2,5],[3,6],[4,7]]}      marathon19

I tried df = df.groupby(['geojson']).apply(list) not really giving something i need

1 Answers

You could use the following approach using geopandas dissolve function on geojson data (a non-geometric approach would involve aggregating, concatenating and parsing the df) :

import json
import geopandas as gpd

data = { "type": "FeatureCollection",
  "features": [
      { "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [3,6],[4,7]
        ]
      },      
       "properties": {
        "checkpoint": 0,
        "prop1": 'marathon19'
      }
      },
    { "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [1,4],[2,5]
        ]
      },
      "properties": {
        "checkpoint": 0,
        "prop1": 'marathon19'
      }
    }
  ]
}

# create geodataframe from geojson-features
gdf = gpd.GeoDataFrame.from_features(data)

# dissolve line strings
gdf = gdf.dissolve()

# convert back to geojson
gdf.to_json()

If the input lines are non-contiguous (like in your example data) you still need to create a linestring out of the resulting multilinestring (see for example and caveats here):

import shapely

# Put the sub-line coordinates into a list of sublists
outcoords = [list(i.coords) for i in gdf.iloc()[0].geometry]

# Flatten the list of sublists and use it to make a new line
outline = shapely.geometry.LineString([i for sublist in outcoords for i in sublist])

# set geometry of gdf to linestring
gdf = gdf.set_geometry([outline])
Related