vibespatial.api.geoseries

Classes

GeoSeries

A Series object designed to store shapely geometry objects.

Module Contents

class vibespatial.api.geoseries.GeoSeries(data=None, index=None, crs: Any | None = None, **kwargs)

A Series object designed to store shapely geometry objects.

Parameters

dataarray-like, dict, scalar value

The geometries to store in the GeoSeries.

indexarray-like or Index

The index for the GeoSeries.

crsvalue (optional)

Coordinate Reference System of the geometry objects. Can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.

kwargs
Additional arguments passed to the Series constructor,

e.g. name.

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
>>> s
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: geometry
>>> s = geopandas.GeoSeries(
...     [Point(1, 1), Point(2, 2), Point(3, 3)], crs="EPSG:3857"
... )
>>> s.crs
<Projected CRS: EPSG:3857>
Name: WGS 84 / Pseudo-Mercator
Axis Info [cartesian]:
- X[east]: Easting (metre)
- Y[north]: Northing (metre)
Area of Use:
- name: World - 85°S to 85°N
- bounds: (-180.0, -85.06, 180.0, 85.06)
Coordinate Operation:
- name: Popular Visualisation Pseudo-Mercator
- method: Popular Visualisation Pseudo Mercator
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
>>> s = geopandas.GeoSeries(
...    [Point(1, 1), Point(2, 2), Point(3, 3)], index=["a", "b", "c"], crs=4326
... )
>>> s
a    POINT (1 1)
b    POINT (2 2)
c    POINT (3 3)
dtype: geometry
>>> s.crs
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World.
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich

See Also

GeoDataFrame pandas.Series

property geometry: GeoSeries
property x: pandas.Series

Return the x location of point geometries in a GeoSeries.

Returns

pandas.Series

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
>>> s.x
0    1.0
1    2.0
2    3.0
dtype: float64

See Also

GeoSeries.y GeoSeries.z

property y: pandas.Series

Return the y location of point geometries in a GeoSeries.

Returns

pandas.Series

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
>>> s.y
0    1.0
1    2.0
2    3.0
dtype: float64

See Also

GeoSeries.x GeoSeries.z GeoSeries.m

property z: pandas.Series

Return the z location of point geometries in a GeoSeries.

Returns

pandas.Series

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1, 1), Point(2, 2, 2), Point(3, 3, 3)])
>>> s.z
0    1.0
1    2.0
2    3.0
dtype: float64

See Also

GeoSeries.x GeoSeries.y GeoSeries.m

property m: pandas.Series

Return the m coordinate of point geometries in a GeoSeries.

Requires Shapely >= 2.1.

Added in version 1.1.0.

Returns

pandas.Series

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries.from_wkt(
...     [
...         "POINT M (2 3 5)",
...         "POINT M (1 2 3)",
...     ]
... )
>>> s
0    POINT M (2 3 5)
1    POINT M (1 2 3)
dtype: geometry
>>> s.m
0    5.0
1    3.0
dtype: float64

See Also

GeoSeries.x GeoSeries.y GeoSeries.z

classmethod from_file(filename: os.PathLike | IO, **kwargs) GeoSeries

Alternate constructor to create a GeoSeries from a file.

Can load a GeoSeries from a file from any format recognized by pyogrio. See http://pyogrio.readthedocs.io/ for details. From a file with attributes loads only geometry column. Note that to do that, GeoPandas first loads the whole GeoDataFrame.

Parameters

filenamestr

File path or file handle to read from. Depending on which kwargs are included, the content of filename may vary. See pyogrio.read_dataframe() for usage details.

kwargskey-word arguments

These arguments are passed to pyogrio.read_dataframe(), and can be used to access multi-layer data, data stored within archives (zip files), etc.

Examples

>>> import geodatasets
>>> path = geodatasets.get_path('nybb')
>>> s = geopandas.GeoSeries.from_file(path)
>>> s
0    MULTIPOLYGON (((970217.022 145643.332, 970227....
1    MULTIPOLYGON (((1029606.077 156073.814, 102957...
2    MULTIPOLYGON (((1021176.479 151374.797, 102100...
3    MULTIPOLYGON (((981219.056 188655.316, 980940....
4    MULTIPOLYGON (((1012821.806 229228.265, 101278...
Name: geometry, dtype: geometry

See Also

read_file : read file to GeoDataFrame

classmethod from_wkb(data, index=None, crs: Any | None = None, on_invalid='raise', **kwargs) GeoSeries

Alternate constructor to create a GeoSeries from a list or array of WKB objects.

Parameters

dataarray-like or Series

Series, list or array of WKB objects

indexarray-like or Index

The index for the GeoSeries.

crsvalue, optional

Coordinate Reference System of the geometry objects. Can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.

on_invalid: {“raise”, “warn”, “ignore”}, default “raise”
  • raise: an exception will be raised if a WKB input geometry is invalid.

  • warn: a warning will be raised and invalid WKB geometries will be returned as None.

  • ignore: invalid WKB geometries will be returned as None without a warning.

  • fix: an effort is made to fix invalid input geometries (e.g. close unclosed rings). If this is not possible, they are returned as None without a warning. Requires GEOS >= 3.11 and shapely >= 2.1.

kwargs

Additional arguments passed to the Series constructor, e.g. name.

Returns

GeoSeries

See Also

GeoSeries.from_wkt

Examples

>>> wkbs = [
... (
...     b"\x01\x01\x00\x00\x00\x00\x00\x00\x00"
...     b"\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?"
... ),
... (
...     b"\x01\x01\x00\x00\x00\x00\x00\x00\x00"
...     b"\x00\x00\x00@\x00\x00\x00\x00\x00\x00\x00@"
... ),
... (
...    b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00"
...    b"\x00\x08@\x00\x00\x00\x00\x00\x00\x08@"
... ),
... ]
>>> s = geopandas.GeoSeries.from_wkb(wkbs)
>>> s
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: geometry
classmethod from_wkt(data, index=None, crs: Any | None = None, on_invalid='raise', **kwargs) GeoSeries

Alternate constructor to create a GeoSeries from a list or array of WKT objects.

Parameters

dataarray-like, Series

Series, list, or array of WKT objects

indexarray-like or Index

The index for the GeoSeries.

crsvalue, optional

Coordinate Reference System of the geometry objects. Can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.

on_invalid{“raise”, “warn”, “ignore”}, default “raise”
  • raise: an exception will be raised if a WKT input geometry is invalid.

  • warn: a warning will be raised and invalid WKT geometries will be returned as None.

  • ignore: invalid WKT geometries will be returned as None without a warning.

  • fix: an effort is made to fix invalid input geometries (e.g. close unclosed rings). If this is not possible, they are returned as None without a warning. Requires GEOS >= 3.11 and shapely >= 2.1.

kwargs

Additional arguments passed to the Series constructor, e.g. name.

Returns

GeoSeries

See Also

GeoSeries.from_wkb

Examples

>>> wkts = [
... 'POINT (1 1)',
... 'POINT (2 2)',
... 'POINT (3 3)',
... ]
>>> s = geopandas.GeoSeries.from_wkt(wkts)
>>> s
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: geometry
classmethod from_xy(x, y, z=None, index=None, crs=None, **kwargs) GeoSeries

Alternate constructor to create a GeoSeries of Point geometries from lists or arrays of x, y(, z) coordinates.

In case of geographic coordinates, it is assumed that longitude is captured by x coordinates and latitude by y.

Parameters

x, y, z : iterable index : array-like or Index, optional

The index for the GeoSeries. If not given and all coordinate inputs are Series with an equal index, that index is used.

crsvalue, optional

Coordinate Reference System of the geometry objects. Can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.

**kwargs

Additional arguments passed to the Series constructor, e.g. name.

Returns

GeoSeries

See Also

GeoSeries.from_wkt points_from_xy

Examples

>>> x = [2.5, 5, -3.0]
>>> y = [0.5, 1, 1.5]
>>> s = geopandas.GeoSeries.from_xy(x, y, crs="EPSG:4326")
>>> s
0    POINT (2.5 0.5)
1    POINT (5 1)
2    POINT (-3 1.5)
dtype: geometry
classmethod from_arrow(arr, **kwargs) GeoSeries

Construct a GeoSeries from an Arrow array object with a GeoArrow extension type.

See https://geoarrow.org/ for details on the GeoArrow specification.

This functions accepts any Arrow array object implementing the Arrow PyCapsule Protocol (i.e. having an __arrow_c_array__ method).

Added in version 1.0.

Parameters

arrpyarrow.Array, Arrow array

Any array object implementing the Arrow PyCapsule Protocol (i.e. has an __arrow_c_array__ or __arrow_c_stream__ method). The type of the array should be one of the geoarrow geometry types.

**kwargs

Other parameters passed to the GeoSeries constructor.

Returns

GeoSeries

See Also

GeoSeries.to_arrow

Examples

>>> import geoarrow.pyarrow as ga
>>> array = ga.as_geoarrow(
... [None, "POLYGON ((0 0, 1 1, 0 1, 0 0))", "LINESTRING (0 0, -1 1, 0 -1)"])
>>> geoseries = geopandas.GeoSeries.from_arrow(array)
>>> geoseries
0                              None
1    POLYGON ((0 0, 1 1, 0 1, 0 0))
2      LINESTRING (0 0, -1 1, 0 -1)
dtype: geometry
to_file(filename: os.PathLike | IO, driver: str | None = None, index: bool | None = None, **kwargs)

Write the GeoSeries to a file.

By default, an ESRI shapefile is written, but any OGR data source supported by Pyogrio or Fiona can be written.

Parameters

filenamestring

File path or file handle to write to. The path may specify a GDAL VSI scheme.

driverstring, default None

The OGR format driver used to write the vector file. If not specified, it attempts to infer it from the file extension. If no extension is specified, it saves ESRI Shapefile to a folder.

indexbool, default None

If True, write index into one or more columns (for MultiIndex). Default None writes the index into one or more columns only if the index is named, is a MultiIndex, or has a non-integer data type. If False, no index is written.

Added in version 0.7: Previously the index was not written.

modestring, default ‘w’

The write mode, ‘w’ to overwrite the existing file and ‘a’ to append. Not all drivers support appending. The drivers that support appending are listed in fiona.supported_drivers or https://github.com/Toblerity/Fiona/blob/master/fiona/drvsupport.py

crspyproj.CRS, default None

If specified, the CRS is passed to Fiona to better control how the file is written. If None, GeoPandas will determine the crs based on crs df attribute. The value can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string. The keyword is not supported for the “pyogrio” engine.

enginestr, “pyogrio” or “fiona”

The underlying library that is used to write the file. Currently, the supported options are “pyogrio” and “fiona”. Defaults to “pyogrio” if installed, otherwise tries “fiona”.

**kwargs :

Keyword args to be passed to the engine, and can be used to write to multi-layer data, store data within archives (zip files), etc. In case of the “pyogrio” engine, the keyword arguments are passed to pyogrio.write_dataframe. In case of the “fiona” engine, the keyword arguments are passed to fiona.open`. For more information on possible keywords, type: import pyogrio; help(pyogrio.write_dataframe).

See Also

GeoDataFrame.to_file : write GeoDataFrame to file read_file : read file to GeoDataFrame

Examples

>>> s.to_file('series.shp')
>>> s.to_file('series.gpkg', driver='GPKG', layer='name1')
>>> s.to_file('series.geojson', driver='GeoJSON')
sort_index(*args, **kwargs)

Sort Series by index labels.

Returns a new Series sorted by label if inplace argument is False, otherwise updates the original series and returns None.

Parameters

axis{0 or ‘index’}

Unused. Parameter needed for compatibility with DataFrame.

levelint, optional

If not None, sort on values in specified index level(s).

ascendingbool or list-like of bools, default True

Sort ascending vs. descending. When the index is a MultiIndex the sort direction can be controlled for each level individually.

inplacebool, default False

If True, perform operation in-place.

kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, default ‘quicksort’

Choice of sorting algorithm. See also numpy.sort() for more information. ‘mergesort’ and ‘stable’ are the only stable algorithms. For DataFrames, this option is only applied when sorting on a single column or label.

na_position{‘first’, ‘last’}, default ‘last’

If ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end. Not implemented for MultiIndex.

sort_remainingbool, default True

If True and sorting by level and index is multilevel, sort by other levels too (in order) after sorting by specified level.

ignore_indexbool, default False

If True, the resulting axis will be labeled 0, 1, …, n - 1.

keycallable, optional

If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape.

Returns

Series or None

The original Series sorted by the labels or None if inplace=True.

See Also

DataFrame.sort_index: Sort DataFrame by the index. DataFrame.sort_values: Sort DataFrame by the value. Series.sort_values : Sort Series by the value.

Examples

>>> s = pd.Series(["a", "b", "c", "d"], index=[3, 2, 1, 4])
>>> s.sort_index()
1    c
2    b
3    a
4    d
dtype: str

Sort Descending

>>> s.sort_index(ascending=False)
4    d
3    a
2    b
1    c
dtype: str

By default NaNs are put at the end, but use na_position to place them at the beginning

>>> s = pd.Series(["a", "b", "c", "d"], index=[3, 2, 1, np.nan])
>>> s.sort_index(na_position="first")
NaN     d
 1.0    c
 2.0    b
 3.0    a
dtype: str

Specify index level to sort

>>> arrays = [
...     np.array(["qux", "qux", "foo", "foo", "baz", "baz", "bar", "bar"]),
...     np.array(["two", "one", "two", "one", "two", "one", "two", "one"]),
... ]
>>> s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8], index=arrays)
>>> s.sort_index(level=1)
bar  one    8
baz  one    6
foo  one    4
qux  one    2
bar  two    7
baz  two    5
foo  two    3
qux  two    1
dtype: int64

Does not sort by remaining levels when sorting by levels

>>> s.sort_index(level=1, sort_remaining=False)
qux  one    2
foo  one    4
baz  one    6
bar  one    8
qux  two    1
foo  two    3
baz  two    5
bar  two    7
dtype: int64

Apply a key function before sorting

>>> s = pd.Series([1, 2, 3, 4], index=["A", "b", "C", "d"])
>>> s.sort_index(key=lambda x: x.str.lower())
A    1
b    2
C    3
d    4
dtype: int64
take(*args, **kwargs)

Return the elements in the given positional indices along an axis.

This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object.

Parameters

indicesarray-like

An array of ints indicating which positions to take.

axis{0 or ‘index’, 1 or ‘columns’}, default 0

The axis on which to select elements. 0 means that we are selecting rows, 1 means that we are selecting columns. For Series this parameter is unused and defaults to 0.

**kwargs

For compatibility with numpy.take(). Has no effect on the output.

Returns

same type as caller

An array-like containing the elements taken from the object.

See Also

DataFrame.loc : Select a subset of a DataFrame by labels. DataFrame.iloc : Select a subset of a DataFrame by positions. numpy.take : Take elements from an array along an axis.

Examples

>>> df = pd.DataFrame(
...     [
...         ("falcon", "bird", 389.0),
...         ("parrot", "bird", 24.0),
...         ("lion", "mammal", 80.5),
...         ("monkey", "mammal", np.nan),
...     ],
...     columns=["name", "class", "max_speed"],
...     index=[0, 2, 3, 1],
... )
>>> df
     name   class  max_speed
0  falcon    bird      389.0
2  parrot    bird       24.0
3    lion  mammal       80.5
1  monkey  mammal        NaN

Take elements at positions 0 and 3 along the axis 0 (default).

Note how the actual indices selected (0 and 1) do not correspond to our selected indices 0 and 3. That’s because we are selecting the 0th and 3rd rows, not rows whose indices equal 0 and 3.

>>> df.take([0, 3])
     name   class  max_speed
0  falcon    bird      389.0
1  monkey  mammal        NaN

Take elements at indices 1 and 2 along the axis 1 (column selection).

>>> df.take([1, 2], axis=1)
    class  max_speed
0    bird      389.0
2    bird       24.0
3  mammal       80.5
1  mammal        NaN

We may take elements using negative integers for positive indices, starting from the end of the object, just like with Python lists.

>>> df.take([-1, -2])
     name   class  max_speed
1  monkey  mammal        NaN
3    lion  mammal       80.5
apply(func, convert_dtype: bool | None = None, args=(), **kwargs)

Invoke function on values of Series.

Can be ufunc (a NumPy function that applies to the entire Series) or a Python function that only works on single values.

Parameters

funcfunction

Python function or NumPy ufunc to apply.

argstuple

Positional arguments passed to func after the series value.

by_rowFalse or “compat”, default “compat”

If "compat" and func is a callable, func will be passed each element of the Series, like Series.map. If func is a list or dict of callables, will first try to translate each func into pandas methods. If that doesn’t work, will try call to apply again with by_row="compat" and if that fails, will call apply again with by_row=False (backward compatible). If False, the func will be passed the whole Series at once.

by_row has no effect when func is a string.

Added in version 2.1.0.

**kwargs

Additional keyword arguments passed to func.

Returns

Series or DataFrame

If func returns a Series object the result will be a DataFrame.

See Also

Series.map: For element-wise operations. Series.agg: Only perform aggregating type operations. Series.transform: Only perform transforming type operations.

Notes

Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See gotchas.udf-mutation for more details.

Examples

Create a series with typical summer temperatures for each city.

>>> s = pd.Series([20, 21, 12], index=["London", "New York", "Helsinki"])
>>> s
London      20
New York    21
Helsinki    12
dtype: int64

Square the values by defining a function and passing it as an argument to apply().

>>> def square(x):
...     return x**2
>>> s.apply(square)
London      400
New York    441
Helsinki    144
dtype: int64

Square the values by passing an anonymous function as an argument to apply().

>>> s.apply(lambda x: x**2)
London      400
New York    441
Helsinki    144
dtype: int64

Define a custom function that needs additional positional arguments and pass these additional arguments using the args keyword.

>>> def subtract_custom_value(x, custom_value):
...     return x - custom_value
>>> s.apply(subtract_custom_value, args=(5,))
London      15
New York    16
Helsinki     7
dtype: int64

Define a custom function that takes keyword arguments and pass these arguments to apply.

>>> def add_custom_values(x, **kwargs):
...     for month in kwargs:
...         x += kwargs[month]
...     return x
>>> s.apply(add_custom_values, june=30, july=20, august=25)
London      95
New York    96
Helsinki    87
dtype: int64

Use a function from the Numpy library.

>>> s.apply(np.log)
London      2.995732
New York    3.044522
Helsinki    2.484907
dtype: float64
isna() pandas.Series

Detect missing values.

Historically, NA values in a GeoSeries could be represented by empty geometric objects, in addition to standard representations such as None and np.nan. This behaviour is changed in version 0.6.0, and now only actual missing values return True. To detect empty geometries, use GeoSeries.is_empty instead.

Returns

A boolean pandas Series of the same size as the GeoSeries, True where a value is NA.

Examples

>>> from shapely.geometry import Polygon
>>> s = geopandas.GeoSeries(
...     [Polygon([(0, 0), (1, 1), (0, 1)]), None, Polygon([])]
... )
>>> s
0    POLYGON ((0 0, 1 1, 0 1, 0 0))
1                              None
2                     POLYGON EMPTY
dtype: geometry
>>> s.isna()
0    False
1     True
2    False
dtype: bool

See Also

GeoSeries.notna : inverse of isna GeoSeries.is_empty : detect empty geometries

isnull() pandas.Series

Alias for isna method. See isna for more detail.

notna() pandas.Series

Detect non-missing values.

Historically, NA values in a GeoSeries could be represented by empty geometric objects, in addition to standard representations such as None and np.nan. This behaviour is changed in version 0.6.0, and now only actual missing values return False. To detect empty geometries, use ~GeoSeries.is_empty instead.

Returns

A boolean pandas Series of the same size as the GeoSeries, False where a value is NA.

Examples

>>> from shapely.geometry import Polygon
>>> s = geopandas.GeoSeries(
...     [Polygon([(0, 0), (1, 1), (0, 1)]), None, Polygon([])]
... )
>>> s
0    POLYGON ((0 0, 1 1, 0 1, 0 0))
1                              None
2                     POLYGON EMPTY
dtype: geometry
>>> s.notna()
0     True
1    False
2     True
dtype: bool

See Also

GeoSeries.isna : inverse of notna GeoSeries.is_empty : detect empty geometries

notnull() pandas.Series

Alias for notna method. See notna for more detail.

fillna(value=None, inplace: bool = False, limit=None, **kwargs)

Fill NA values with geometry (or geometries).

Parameters

valueshapely geometry or GeoSeries, default None

If None is passed, NA values will be filled with GEOMETRYCOLLECTION EMPTY. If a shapely geometry object is passed, it will be used to fill all missing values. If a GeoSeries or GeometryArray are passed, missing values will be filled based on the corresponding index locations. If pd.NA or np.nan are passed, values will be filled with None (not GEOMETRYCOLLECTION EMPTY).

limitint, default None

This is the maximum number of entries along the entire axis where NaNs will be filled. Must be greater than 0 if not None.

Returns

GeoSeries

Examples

>>> from shapely.geometry import Polygon
>>> s = geopandas.GeoSeries(
...     [
...         Polygon([(0, 0), (1, 1), (0, 1)]),
...         None,
...         Polygon([(0, 0), (-1, 1), (0, -1)]),
...     ]
... )
>>> s
0      POLYGON ((0 0, 1 1, 0 1, 0 0))
1                                None
2    POLYGON ((0 0, -1 1, 0 -1, 0 0))
dtype: geometry

Filled with an empty polygon.

>>> s.fillna()
0      POLYGON ((0 0, 1 1, 0 1, 0 0))
1            GEOMETRYCOLLECTION EMPTY
2    POLYGON ((0 0, -1 1, 0 -1, 0 0))
dtype: geometry

Filled with a specific polygon.

>>> s.fillna(Polygon([(0, 1), (2, 1), (1, 2)]))
0      POLYGON ((0 0, 1 1, 0 1, 0 0))
1      POLYGON ((0 1, 2 1, 1 2, 0 1))
2    POLYGON ((0 0, -1 1, 0 -1, 0 0))
dtype: geometry

Filled with another GeoSeries.

>>> from shapely.geometry import Point
>>> s_fill = geopandas.GeoSeries(
...     [
...         Point(0, 0),
...         Point(1, 1),
...         Point(2, 2),
...     ]
... )
>>> s.fillna(s_fill)
0      POLYGON ((0 0, 1 1, 0 1, 0 0))
1                         POINT (1 1)
2    POLYGON ((0 0, -1 1, 0 -1, 0 0))
dtype: geometry

See Also

GeoSeries.isna : detect missing values

plot(*args, **kwargs)
explore(*args, **kwargs)

Explore with an interactive map based on folium/leaflet.js.

explode(ignore_index=False, index_parts=False) GeoSeries

Explode multi-part geometries into multiple single geometries.

Single rows can become multiple rows. This is analogous to PostGIS’s ST_Dump(). The ‘path’ index is the second level of the returned MultiIndex

Parameters

ignore_indexbool, default False

If True, the resulting index will be labelled 0, 1, …, n - 1, ignoring index_parts.

index_partsboolean, default False

If True, the resulting index will be a multi-index (original index with an additional level indicating the multiple geometries: a new zero-based index for each single part geometry per multi-part geometry).

Returns

A GeoSeries with a MultiIndex. The levels of the MultiIndex are the original index and a zero-based integer index that counts the number of single geometries within a multi-part geometry.

Examples

>>> from shapely.geometry import MultiPoint
>>> s = geopandas.GeoSeries(
...     [MultiPoint([(0, 0), (1, 1)]), MultiPoint([(2, 2), (3, 3), (4, 4)])]
... )
>>> s
0           MULTIPOINT ((0 0), (1 1))
1    MULTIPOINT ((2 2), (3 3), (4 4))
dtype: geometry
>>> s.explode(index_parts=True)
0  0    POINT (0 0)
   1    POINT (1 1)
1  0    POINT (2 2)
   1    POINT (3 3)
   2    POINT (4 4)
dtype: geometry

See Also

GeoDataFrame.explode

set_crs(crs: Any | None = None, epsg: int | None = None, inplace: bool = False, allow_override: bool = False)

Set the Coordinate Reference System (CRS) of a GeoSeries.

Pass None to remove CRS from the GeoSeries.

Notes

The underlying geometries are not transformed to this CRS. To transform the geometries to a new CRS, use the to_crs method.

Parameters

crspyproj.CRS | None, optional

The value can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.

epsgint, optional if crs is specified

EPSG code specifying the projection.

inplacebool, default False

If True, the CRS of the GeoSeries will be changed in place (while still returning the result) instead of making a copy of the GeoSeries.

allow_overridebool, default False

If the the GeoSeries already has a CRS, allow to replace the existing CRS, even when both are not equal.

Returns

GeoSeries

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
>>> s
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: geometry

Setting CRS to a GeoSeries without one:

>>> s.crs is None
True
>>> s = s.set_crs('epsg:3857')
>>> s.crs
<Projected CRS: EPSG:3857>
Name: WGS 84 / Pseudo-Mercator
Axis Info [cartesian]:
- X[east]: Easting (metre)
- Y[north]: Northing (metre)
Area of Use:
- name: World - 85°S to 85°N
- bounds: (-180.0, -85.06, 180.0, 85.06)
Coordinate Operation:
- name: Popular Visualisation Pseudo-Mercator
- method: Popular Visualisation Pseudo Mercator
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich

Overriding existing CRS:

>>> s = s.set_crs(4326, allow_override=True)

Without allow_override=True, set_crs returns an error if you try to override CRS.

See Also

GeoSeries.to_crs : re-project to another CRS

to_crs(crs: Any | None = None, epsg: int | None = None) GeoSeries

Return a GeoSeries with all geometries transformed to a new coordinate reference system.

Transform all geometries in a GeoSeries to a different coordinate reference system. The crs attribute on the current GeoSeries must be set. Either crs or epsg may be specified for output.

This method will transform all points in all objects. It has no notion of projecting entire geometries. All segments joining points are assumed to be lines in the current projection, not geodesics. Objects crossing the dateline (or other projection boundary) will have undesirable behavior.

Parameters

crspyproj.CRS, optional if epsg is specified

The value can be anything accepted by pyproj.CRS.from_user_input(), such as an authority string (eg “EPSG:4326”) or a WKT string.

epsgint, optional if crs is specified

EPSG code specifying output projection.

Returns

GeoSeries

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)], crs=4326)
>>> s
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: geometry
>>> s.crs
<Geographic 2D CRS: EPSG:4326>
Name: WGS 84
Axis Info [ellipsoidal]:
- Lat[north]: Geodetic latitude (degree)
- Lon[east]: Geodetic longitude (degree)
Area of Use:
- name: World
- bounds: (-180.0, -90.0, 180.0, 90.0)
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
>>> s = s.to_crs(3857)
>>> s
0    POINT (111319.491 111325.143)
1    POINT (222638.982 222684.209)
2    POINT (333958.472 334111.171)
dtype: geometry
>>> s.crs
<Projected CRS: EPSG:3857>
Name: WGS 84 / Pseudo-Mercator
Axis Info [cartesian]:
- X[east]: Easting (metre)
- Y[north]: Northing (metre)
Area of Use:
- name: World - 85°S to 85°N
- bounds: (-180.0, -85.06, 180.0, 85.06)
Coordinate Operation:
- name: Popular Visualisation Pseudo-Mercator
- method: Popular Visualisation Pseudo Mercator
Datum: World Geodetic System 1984
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich

See Also

GeoSeries.set_crs : assign CRS

estimate_utm_crs(datum_name: str = 'WGS 84')

Return the estimated UTM CRS based on the bounds of the dataset.

Added in version 0.9.

Parameters

datum_namestr, optional

The name of the datum to use in the query. Default is WGS 84.

Returns

pyproj.CRS

Examples

>>> import geodatasets
>>> df = geopandas.read_file(
...     geodatasets.get_path("geoda.chicago_health")
... )
>>> df.geometry.estimate_utm_crs()
<Derived Projected CRS: EPSG:32616>
Name: WGS 84 / UTM zone 16N
Axis Info [cartesian]:
- E[east]: Easting (metre)
- N[north]: Northing (metre)
Area of Use:
- name: Between 90°W and 84°W, northern hemisphere between equator and 84°N, ...
- bounds: (-90.0, 0.0, -84.0, 84.0)
Coordinate Operation:
- name: UTM zone 16N
- method: Transverse Mercator
Datum: World Geodetic System 1984 ensemble
- Ellipsoid: WGS 84
- Prime Meridian: Greenwich
to_json(show_bbox: bool = True, drop_id: bool = False, to_wgs84: bool = False, **kwargs) str

Return a GeoJSON string representation of the GeoSeries.

Parameters

show_bboxbool, optional, default: True

Include bbox (bounds) in the geojson

drop_idbool, default: False

Whether to retain the index of the GeoSeries as the id property in the generated GeoJSON. Default is False, but may want True if the index is just arbitrary row numbers.

to_wgs84: bool, optional, default: False

If the CRS is set on the active geometry column it is exported as WGS84 (EPSG:4326) to meet the 2016 GeoJSON specification. Set to True to force re-projection and set to False to ignore CRS. False by default.

kwargs that will be passed to json.dumps().

Returns

JSON string

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
>>> s
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: geometry
>>> s.to_json()
'{"type": "FeatureCollection", "features": [{"id": "0", "type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [1.0, 1.0]}, "bbox": [1.0, 1.0, 1.0, 1.0]}, {"id": "1", "type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [2.0, 2.0]}, "bbox": [2.0, 2.0, 2.0, 2.0]}, {"id": "2", "type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [3.0, 3.0]}, "bbox": [3.0, 3.0, 3.0, 3.0]}], "bbox": [1.0, 1.0, 3.0, 3.0]}'

See Also

GeoSeries.to_file : write GeoSeries to file

to_wkb(hex: bool = False, **kwargs) pandas.Series

Convert GeoSeries geometries to WKB.

Parameters

hexbool

If true, export the WKB as a hexadecimal string. The default is to return a binary bytes object.

kwargs

Additional keyword args will be passed to shapely.to_wkb().

Returns

Series

WKB representations of the geometries

See Also

GeoSeries.to_wkt

Examples

>>> from shapely.geometry import Point, Polygon
>>> s = geopandas.GeoSeries(
...     [
...         Point(0, 0),
...         Polygon(),
...         Polygon([(0, 0), (1, 1), (1, 0)]),
...         None,
...     ]
... )
>>> s.to_wkb()
0    b'\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00...
1              b'\x01\x03\x00\x00\x00\x00\x00\x00\x00'
2    b'\x01\x03\x00\x00\x00\x01\x00\x00\x00\x04\x00...
3                                                 None
dtype: object
>>> s.to_wkb(hex=True)
0           010100000000000000000000000000000000000000
1                                   010300000000000000
2    0103000000010000000400000000000000000000000000...
3                                                  NaN
dtype: str
to_wkt(**kwargs) pandas.Series

Convert GeoSeries geometries to WKT.

Parameters

kwargs

Keyword args will be passed to shapely.to_wkt().

Returns

Series

WKT representations of the geometries

Examples

>>> from shapely.geometry import Point
>>> s = geopandas.GeoSeries([Point(1, 1), Point(2, 2), Point(3, 3)])
>>> s
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: geometry
>>> s.to_wkt()
0    POINT (1 1)
1    POINT (2 2)
2    POINT (3 3)
dtype: str

See Also

GeoSeries.to_wkb

to_arrow(geometry_encoding='WKB', interleaved=True, include_z=None)

Encode a GeoSeries to GeoArrow format.

See https://geoarrow.org/ for details on the GeoArrow specification.

This functions returns a generic Arrow array object implementing the Arrow PyCapsule Protocol (i.e. having an __arrow_c_array__ method). This object can then be consumed by your Arrow implementation of choice that supports this protocol.

Added in version 1.0.

Parameters

geometry_encoding{‘WKB’, ‘geoarrow’ }, default ‘WKB’

The GeoArrow encoding to use for the data conversion.

interleavedbool, default True

Only relevant for ‘geoarrow’ encoding. If True, the geometries’ coordinates are interleaved in a single fixed size list array. If False, the coordinates are stored as separate arrays in a struct type.

include_zbool, default None

Only relevant for ‘geoarrow’ encoding (for WKB, the dimensionality of the individual geometries is preserved). If False, return 2D geometries. If True, include the third dimension in the output (if a geometry has no third dimension, the z-coordinates will be NaN). By default, will infer the dimensionality from the input geometries. Note that this inference can be unreliable with empty geometries (for a guaranteed result, it is recommended to specify the keyword).

Returns

GeoArrowArray

A generic Arrow array object with geometry data encoded to GeoArrow.

Examples

>>> from shapely.geometry import Point
>>> gser = geopandas.GeoSeries([Point(1, 2), Point(2, 1)])
>>> gser
0    POINT (1 2)
1    POINT (2 1)
dtype: geometry
>>> arrow_array = gser.to_arrow()
>>> arrow_array
<geopandas.io._geoarrow.GeoArrowArray object at ...>

The returned array object needs to be consumed by a library implementing the Arrow PyCapsule Protocol. For example, wrapping the data as a pyarrow.Array (requires pyarrow >= 14.0):

>>> import pyarrow as pa
>>> array = pa.array(arrow_array)
>>> array
GeometryExtensionArray:WkbType(geoarrow.wkb)[2]
<POINT (1 2)>
<POINT (2 1)>
clip(mask, keep_geom_type: bool = False, sort=False) GeoSeries

Clip points, lines, or polygon geometries to the mask extent.

Both layers must be in the same Coordinate Reference System (CRS). The GeoSeries will be clipped to the full extent of the mask object.

If there are multiple polygons in mask, data from the GeoSeries will be clipped to the total boundary of all polygons in mask.

Parameters

maskGeoDataFrame, GeoSeries, (Multi)Polygon, list-like

Polygon vector layer used to clip gdf. The mask’s geometry is dissolved into one geometric feature and intersected with GeoSeries. If the mask is list-like with four elements (minx, miny, maxx, maxy), clip will use a faster rectangle clipping (clip_by_rect()), possibly leading to slightly different results.

keep_geom_typeboolean, default False

If True, return only geometries of original type in case of intersection resulting in multiple geometry types or GeometryCollections. If False, return all resulting geometries (potentially mixed-types).

sortboolean, default False

If True, the order of rows in the clipped GeoSeries will be preserved at small performance cost. If False the order of rows in the clipped GeoSeries will be random.

Returns

GeoSeries

Vector data (points, lines, polygons) from gdf clipped to polygon boundary from mask.

See Also

clip : top-level function for clip

Examples

Clip points (grocery stores) with polygons (the Near West Side community):

>>> import geodatasets
>>> chicago = geopandas.read_file(
...     geodatasets.get_path("geoda.chicago_health")
... )
>>> near_west_side = chicago[chicago["community"] == "NEAR WEST SIDE"]
>>> groceries = geopandas.read_file(
...     geodatasets.get_path("geoda.groceries")
... ).to_crs(chicago.crs)
>>> groceries.shape
(148, 8)
>>> nws_groceries = groceries.geometry.clip(near_west_side)
>>> nws_groceries.shape
(7,)