Applying custom spatial operations

Lavorare con i dati geospaziali in Python

Joris Van den Bossche

Open source software developer and teacher, GeoPandas maintainer

Lavorare con i dati geospaziali in Python

Total river length within 50 km of each city?

For a single point (cairo):

area = cairo.buffer(50000)

rivers_within_area = rivers.intersection(area)
print(rivers_within_area.length.sum() / 1000)
186.397219642
Lavorare con i dati geospaziali in Python

The apply() method

Series.apply(): call a function on each of the values of the Series

Series.apply(function, **kwargs)

  • function: the function being called on each value; the value is passed as the first argument
  • **kwargs: additional arguments passed to the function

For a GeoSeries, the function is called as function(geom, **kwargs) for each geom in the GeoSeries

Lavorare con i dati geospaziali in Python

Applying a custom spatial operation

The function to apply:

def river_length(geom, rivers):
    area = geom.buffer(50000)
    rivers_within_area = rivers.intersection(area)
    return rivers_within_area.length.sum() / 1000

Call function on the single geometry:

river_length(cairo, rivers=rivers)
186.3972196423455

Applying on all cities:

cities.geometry.apply(river_length, rivers=rivers)
Lavorare con i dati geospaziali in Python

Applying a custom spatial operation

Applying on all cities:

cities.geometry.apply(river_length, rivers=rivers)
0        0.000000
1        0.000000
2      106.072198
          ...    
Lavorare con i dati geospaziali in Python

Applying a custom spatial operation

Applying on all cities and assigning result to new column:

cities['river_length'] = cities.geometry.apply(river_length, rivers=rivers)
cities.head()
             name                       geometry  river_length
0    Vatican City    POINT (1386304.6 5146502.5)      0.000000
1      San Marino    POINT (1385011.5 5455558.1)      0.000000
2           Vaduz    POINT (1059390.7 5963928.5)    106.072198
..            ...                            ...           ...
Lavorare con i dati geospaziali in Python

Let's practice!

Lavorare con i dati geospaziali in Python

Preparing Video For Download...