1

I have a dataframe containing GeoJSON:

   geojson                                       checkpoint    lom_name
    {"type":"LineString","coordinates":[[1,4],[2,5]]}   6   marathon19
    ("type":"LineString","coordinates":[[3,6],[4,7]]}   0   marathon19

The desired result is:

   geojson                                                             lom_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

0

1 Answer 1

1

Here is a complete working code for your problem. First, I loaded geojson to geodataframe. Then, I iterated through each feature and check if lom_name matches to the one for which lines are being merged.

Then I created Shapely MultiLineString from array of LineStrings.

Hope this is what you were looking for.

import json
import geopandas as gpd
from shapely import geometry


def merge_gdf(name):
    l_seg = json.loads("""
     {
        "type": "FeatureCollection",
        "features": [{
            "type": "Feature",
            "properties": {
                "checkpoint": 6,
                "lom_name": "marathon19"
            },
            "geometry": {
                "type": "LineString",
                "coordinates": [
                    [1, 4],
                    [2, 5]
                ]
            }
        }, {
            "type": "Feature",
            "properties": {
                "checkpoint": 0,
                "lom_name": "marathon19"
            },
            "geometry": {
                "type": "LineString",
                "coordinates": [
                    [3, 6],
                    [4, 7]
                ]
            }
        }, {
            "type": "Feature",
            "properties": {
                "checkpoint": 0,
                "lom_name": "marathon20"
            },
            "geometry": {
                "type": "LineString",
                "coordinates": [
                    [6, 8],
                    [10, 12]
                ]
            }
        }]
    }
    """)
    line_segments = []
    gdf = gpd.GeoDataFrame.from_features(l_seg["features"])
    print(gdf.head())

    for idx, row in gdf.iterrows():
        if row['lom_name'] == name:
            line_segments.append(row['geometry'])

    multiline = geometry.MultiLineString(line_segments)
    print(multiline)

    gs = gpd.GeoSeries(multiline)
    print(gs.to_json())


if __name__ == '__main__':
    merge_gdf('marathon19')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.