shapely.transform

Contents

shapely.transform#

transform(geometry, transformation, include_z: bool | None = False, interleaved: bool = True)#

Returns a copy of a geometry array with a function applied to its coordinates.

With the default of include_z=False, all returned geometries will be two-dimensional; the third dimension will be discarded, if present. When specifying include_z=True, the returned geometries preserve the dimensionality of the respective input geometries.

Parameters:
geometryGeometry or array_like
transformationfunction

A function that transforms a (N, 2) or (N, 3) ndarray of float64 to another (N, 2) or (N, 3) ndarray of float64. The function may not change N.

include_zbool, optional, default False

If False, always return 2D geometries. If True, the data being passed to the transformation function will include the third dimension (if a geometry has no third dimension, the z-coordinates will be NaN). If None, will infer the dimensionality per input geometry using has_z, which may result in 2 calls to the transformation function. Note that this inference can be unreliable with empty geometries or NaN coordinates: for a guaranteed result, it is recommended to specify include_z explicitly.

interleavedbool, default True

If set to False, the transformation function should accept 2 or 3 separate one-dimensional arrays (x, y and optional z) instead of a single two-dimensional array.

New in version 2.1.0.

See also

has_z

Returns a copy of a geometry array with a function applied to its coordinates.

Examples

>>> from shapely import LineString, Point
>>> transform(Point(0, 0), lambda x: x + 1)
<POINT (1 1)>
>>> transform(LineString([(2, 2), (4, 4)]), lambda x: x * [2, 3])
<LINESTRING (4 6, 8 12)>
>>> transform(None, lambda x: x) is None
True
>>> transform([Point(0, 0), None], lambda x: x).tolist()
[<POINT (0 0)>, None]

The presence of a third dimension can be automatically detected, or controlled explicitly:

>>> transform(Point(0, 0, 0), lambda x: x + 1)
<POINT (1 1)>
>>> transform(Point(0, 0, 0), lambda x: x + 1, include_z=True)
<POINT Z (1 1 1)>
>>> transform(Point(0, 0, 0), lambda x: x + 1, include_z=None)
<POINT Z (1 1 1)>

With interleaved=False, the call signature of the transformation is different:

>>> transform(LineString([(1, 2), (3, 4)]), lambda x, y: (x + 1, y), interleaved=False)
<LINESTRING (2 2, 4 4)>

Or with a z coordinate:

>>> transform(Point(0, 0, 0), lambda x, y, z: (x + 1, y, z + 2), interleaved=False, include_z=True)
<POINT Z (1 0 2)>

Using pyproj >= 2.1, the following example will reproject Shapely geometries from EPSG 4326 to EPSG 32618:

>>> from pyproj import Transformer
>>> transformer = Transformer.from_crs(4326, 32618, always_xy=True)
>>> transform(Point(-75, 50), transformer.transform, interleaved=False)
<POINT (500000 5538630.703)>