1

I want to get a new GeoDataFrame in which each element is the union of N consecutive elements in my original GeoDataFrame. I'd be very happy if this code worked, but it doesn't: the last step fails.

from shapely.geometry import Polygon
from shapely.ops import unary_union
import geopandas as gpd

p1 = Polygon([(1,1),(1,2),(2,2)]) p2 = Polygon([(1,1),(2,2),(2,1)]) p3 = Polygon([(1,1),(2,1),(2,0)]) gdf = gpd.GeoDataFrame(geometry=[p1, p2, p3])

gdf.rolling(window=2).apply(unary_union)

I would expect something that behaves like this

import pandas as pd
df = pd.DataFrame({'numbers': [1,2,3]})
df.rolling(window=2).apply(sum)

Out[1]: numbers 0 NaN 1 3.0 2 5.0

matiasg
  • 113
  • 4

1 Answers1

1

You can solve it like this:

from shapely.geometry import Polygon
from shapely.ops import unary_union
import geopandas as gpd
import numpy as np

p1 = Polygon([(1,1),(1,2),(2,2)]) p2 = Polygon([(1,1),(2,2),(2,1)]) p3 = Polygon([(1,1),(2,1),(2,0)]) gdf = gpd.GeoDataFrame(geometry=[p1, p2, p3])

#gdf.rolling(window=2).apply(unary_union) #DataError: Cannot aggregate non-numeric type: geometry

rolling_window = gdf.rolling(window=2)

#Create a list of lists with geometry pairs in each sublist geometry_pairs = [[*l.geometry] for l in rolling_window if len(l) == 2] #https://stackoverflow.com/questions/70670079/get-indexes-of-pandas-rolling-window unions = [unary_union(pair) for pair in geometry_pairs] unions.insert(0, np.nan)

[nan,

<POLYGON ((1 2, 2 2, 2 1, 1 1, 1 2))>,

<POLYGON ((2 0, 1 1, 2 2, 2 1, 2 0))>]

BERA
  • 72,339
  • 13
  • 72
  • 161