You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by ji...@apache.org on 2026/07/28 04:43:33 UTC
(sedona) branch master updated: [GH-3181] GeoPandas: Implement distributed dissolve and tools.collect (#3185)
This is an automated email from the ASF dual-hosted git repository.
jiayuasu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sedona.git
The following commit(s) were added to refs/heads/master by this push:
new 4b8eb93323f [GH-3181] GeoPandas: Implement distributed dissolve and tools.collect (#3185)
4b8eb93323f is described below
commit 4b8eb93323fc4dcada89340a330292d7f03b9842
Author: Jia Yu <ji...@apache.org>
AuthorDate: Mon Jul 27 21:43:28 2026 -0700
[GH-3181] GeoPandas: Implement distributed dissolve and tools.collect (#3185)
---
docs/tutorial/geopandas-api.md | 30 +
docs/tutorial/geopandas-api.zh.md | 28 +
python/sedona/spark/geopandas/geodataframe.py | 760 +++++++++++++++++++++
python/sedona/spark/geopandas/geoseries.py | 7 +-
python/sedona/spark/geopandas/tools/__init__.py | 4 +-
python/sedona/spark/geopandas/tools/collect.py | 146 ++++
.../tests/geopandas/test_geometry_aggregation.py | 604 ++++++++++++++++
7 files changed, 1577 insertions(+), 2 deletions(-)
diff --git a/docs/tutorial/geopandas-api.md b/docs/tutorial/geopandas-api.md
index 03a3aa6db66..22b6963771b 100644
--- a/docs/tutorial/geopandas-api.md
+++ b/docs/tutorial/geopandas-api.md
@@ -341,6 +341,36 @@ The GeoPandas API for Apache Sedona implements the most commonly used GeoSeries
- `clip()` - Distributed geometry clipping
- `sindex` - Spatial indexing (limited functionality)
+### Distributed Geometry Aggregation
+
+- `GeoDataFrame.dissolve()` - Group rows and union each group's geometries
+ with Sedona's native distributed aggregate
+- `sedona.spark.geopandas.tools.collect()` - Collect a distributed GeoSeries
+ into one geometry, using a homogeneous multipart geometry when needed
+
+```python
+from sedona.spark.geopandas.tools import collect
+
+by_region = buildings.dissolve(
+ by="region",
+ aggfunc={"population": "sum", "name": "first"},
+)
+all_building_parts = collect(buildings.geometry)
+```
+
+`dissolve` supports the `unary` union method. Fixed-precision `grid_size`,
+`coverage`, and `disjoint_subset` unions are rejected explicitly. Multiple
+attribute aggregations remain a two-level pandas-on-Spark `MultiIndex`;
+GeoPandas instead represents their tuple labels in a one-level object index.
+Native `first`, `last`, and `count` aggregation supports every attribute type;
+`nunique` supports numeric, boolean, and string columns; and `min`, `max`,
+`sum`, `mean`, `median`, `std`, and `var` support numeric and boolean columns.
+String `sum` and every `prod` aggregation are rejected explicitly. Callable
+aliases are limited to built-in `min`, `max`, and `sum`, plus NumPy `amin`,
+`amax`, `min`, `max`, `sum`, `mean`, `median`, `std`, and `var`.
+Both operations aggregate input rows on Spark executors. `collect` transfers
+only aggregate metadata and the API's single geometry result to the driver.
+
### Data Conversion
- `to_geopandas()` - Convert to traditional GeoPandas
diff --git a/docs/tutorial/geopandas-api.zh.md b/docs/tutorial/geopandas-api.zh.md
index a85e5f7570b..5100ea351c0 100644
--- a/docs/tutorial/geopandas-api.zh.md
+++ b/docs/tutorial/geopandas-api.zh.md
@@ -341,6 +341,34 @@ Apache Sedona 的 GeoPandas API 已实现最常用的 GeoSeries 与 GeoDataFrame
- `clip()` —— 分布式几何裁剪
- `sindex` —— 空间索引(功能有限)
+### 分布式几何聚合
+
+- `GeoDataFrame.dissolve()` —— 对行进行分组,并使用 Sedona 原生分布式聚合
+ 对每组几何执行并集
+- `sedona.spark.geopandas.tools.collect()` —— 将分布式 GeoSeries 聚合为一个
+ 几何,并在需要时使用同构多部件几何
+
+```python
+from sedona.spark.geopandas.tools import collect
+
+by_region = buildings.dissolve(
+ by="region",
+ aggfunc={"population": "sum", "name": "first"},
+)
+all_building_parts = collect(buildings.geometry)
+```
+
+`dissolve` 支持 `unary` 并集方法,并会明确拒绝定点精度 `grid_size`、
+`coverage` 与 `disjoint_subset` 并集。多个属性聚合会保留为 pandas-on-Spark
+的两级 `MultiIndex`;GeoPandas 则把对应元组标签放在单级 object 索引中。
+原生 `first`、`last` 与 `count` 聚合支持所有属性类型;`nunique` 支持数值、
+布尔与字符串列;`min`、`max`、`sum`、`mean`、`median`、`std` 与 `var`
+支持数值和布尔列。字符串 `sum` 与所有 `prod` 聚合都会被明确拒绝。可调用
+聚合仅限 Python 内置的 `min`、`max`、`sum`,以及 NumPy 的 `amin`、
+`amax`、`min`、`max`、`sum`、`mean`、`median`、`std` 与 `var`。
+两个操作都在 Spark executor 上聚合输入行。`collect` 只会把聚合元数据和
+该 API 所需的单个几何结果传输到 driver。
+
### 数据转换
- `to_geopandas()` —— 转换为传统 GeoPandas
diff --git a/python/sedona/spark/geopandas/geodataframe.py b/python/sedona/spark/geopandas/geodataframe.py
index 52681ec7489..eb742f968d7 100644
--- a/python/sedona/spark/geopandas/geodataframe.py
+++ b/python/sedona/spark/geopandas/geodataframe.py
@@ -16,6 +16,7 @@
# under the License.
from __future__ import annotations
+import builtins
from typing import Any, Literal, Callable, Union
import typing
@@ -29,10 +30,31 @@ import pyspark.pandas as pspd
import sedona.spark.geopandas as sgpd
from pyspark.pandas import Series as PandasOnSparkSeries
from pyspark.pandas.frame import DataFrame as PandasOnSparkDataFrame
+from pyspark.pandas.internal import (
+ InternalField,
+ InternalFrame,
+ NATURAL_ORDER_COLUMN_NAME,
+ SPARK_INDEX_NAME_FORMAT,
+)
+from pyspark.pandas.utils import scol_for
+from pyspark.sql import functions as F
+from pyspark.sql.types import (
+ BooleanType,
+ ByteType,
+ DoubleType,
+ FloatType,
+ IntegerType,
+ LongType,
+ NumericType,
+ ShortType,
+ StringType,
+)
from pyspark.pandas.utils import log_advice
from sedona.spark.geopandas._typing import Label
from sedona.spark.geopandas.base import GeoFrame
+from sedona.spark.sql import st_aggregates as sta
+from sedona.spark.sql import st_constructors as stc
from pandas.api.extensions import register_extension_dtype
from geopandas.geodataframe import crs_mismatch_error
@@ -118,6 +140,359 @@ def _not_implemented_error(method_name: str, additional_info: str = "") -> str:
return base_message + workaround
+def _normalize_dissolve_aggfunc(aggfunc):
+ """Translate explicitly supported callables to native aggregate names."""
+
+ supported_names = {
+ "count",
+ "first",
+ "last",
+ "max",
+ "mean",
+ "median",
+ "min",
+ "nunique",
+ "std",
+ "sum",
+ "var",
+ }
+ callable_names = (
+ (builtins.max, "max"),
+ (builtins.min, "min"),
+ (builtins.sum, "sum"),
+ (np.amax, "max"),
+ (np.amin, "min"),
+ (np.max, "max"),
+ (np.mean, "mean"),
+ (np.median, "median"),
+ (np.min, "min"),
+ (np.std, "std"),
+ (np.sum, "sum"),
+ (np.var, "var"),
+ )
+
+ def normalize_one(value):
+ if isinstance(value, str):
+ if value in {"prod", "product"}:
+ raise NotImplementedError(
+ "Sedona dissolve does not support the prod aggregation."
+ )
+ if value not in supported_names:
+ raise NotImplementedError(
+ f"Sedona dissolve does not support the {value!r} aggregation."
+ )
+ return value
+ for known_callable, name in callable_names:
+ if value is known_callable:
+ return name
+ if value is np.prod:
+ raise NotImplementedError(
+ "Sedona dissolve does not support the prod aggregation."
+ )
+ raise NotImplementedError(
+ "Sedona dissolve only supports documented aggregation names and "
+ "known built-in or NumPy aggregation callables."
+ )
+
+ if isinstance(aggfunc, dict):
+ return {
+ key: (
+ [normalize_one(value) for value in values]
+ if isinstance(values, (list, tuple))
+ else normalize_one(values)
+ )
+ for key, values in aggfunc.items()
+ }
+ if isinstance(aggfunc, (list, tuple)):
+ return [normalize_one(value) for value in aggfunc]
+ return normalize_one(aggfunc)
+
+
+class _DissolveGroupers(typing.NamedTuple):
+ expressions: list
+ fields: list
+ index_names: list
+ column_labels: list
+
+
+def _resolve_dissolve_groupers(
+ frame,
+ internal,
+ geometry_label,
+ by,
+ level,
+ observed,
+):
+ """Resolve dissolve groupers without constructing the aggregation plan."""
+
+ group_expressions = []
+ group_fields = []
+ group_index_names = []
+ grouped_column_labels = []
+
+ if level is not None:
+ levels = list(level) if isinstance(level, (list, tuple)) else [level]
+ index_names = list(internal.index_names)
+
+ def level_position(value):
+ if isinstance(value, (int, np.integer)):
+ position = int(value)
+ if position < 0:
+ position += len(index_names)
+ if position < 0 or position >= len(index_names):
+ raise IndexError(
+ f"Too many levels: Index has only {len(index_names)} levels"
+ )
+ return position
+
+ wanted = value if isinstance(value, tuple) else (value,)
+ matches = [
+ position for position, name in enumerate(index_names) if name == wanted
+ ]
+ if not matches:
+ raise KeyError(f"Level {value} not found")
+ if len(matches) > 1:
+ raise ValueError(
+ f"The name {value} occurs multiple times, use a level number"
+ )
+ return matches[0]
+
+ positions = [level_position(value) for value in levels]
+ for position in positions:
+ group_expressions.append(internal.index_spark_columns[position])
+ group_fields.append(internal.index_fields[position])
+ group_index_names.append(internal.index_names[position])
+ elif by is None:
+ group_expressions.append(F.lit(0).cast("long"))
+ group_fields.append(None)
+ group_index_names.append(None)
+ else:
+ groupers_are_column_labels = True
+ if isinstance(by, PandasOnSparkSeries):
+ groupers = [by]
+ groupers_are_column_labels = False
+ if by._psdf is not frame:
+ raise NotImplementedError(
+ "Sedona dissolve requires Series groupers to come from "
+ "the GeoDataFrame being dissolved."
+ )
+ else:
+ try:
+ candidate = frame[by]
+ except (KeyError, TypeError):
+ candidate = None
+
+ if isinstance(candidate, PandasOnSparkSeries):
+ groupers = [candidate]
+ elif isinstance(by, list):
+ groupers = []
+ for key in by:
+ try:
+ grouper = frame[key]
+ except (KeyError, TypeError) as exc:
+ raise NotImplementedError(
+ "Sedona dissolve supports column labels, not "
+ "driver-side grouping vectors."
+ ) from exc
+ if not isinstance(grouper, PandasOnSparkSeries):
+ raise ValueError(f"Grouper for '{key}' is not 1-dimensional")
+ groupers.append(grouper)
+ else:
+ raise NotImplementedError(
+ "Sedona dissolve supports column labels, not driver-side "
+ "grouping vectors."
+ )
+
+ for grouper in groupers:
+ if grouper._column_label == geometry_label:
+ raise NotImplementedError(
+ "Grouping by the active geometry column is not supported."
+ )
+ group_expressions.append(internal.spark_column_for(grouper._column_label))
+ group_fields.append(internal.field_for(grouper._column_label))
+ group_index_names.append(grouper._column_label)
+ if groupers_are_column_labels:
+ grouped_column_labels.append(grouper._column_label)
+
+ if not group_expressions:
+ raise ValueError("No group keys passed")
+
+ if not observed:
+ categorical_groupers = [
+ field
+ for field in group_fields
+ if field is not None and isinstance(field.dtype, pd.CategoricalDtype)
+ ]
+ if categorical_groupers:
+ raise NotImplementedError(
+ "Sedona dissolve cannot materialize unobserved categorical "
+ "groups; pass observed=True."
+ )
+
+ return _DissolveGroupers(
+ group_expressions,
+ group_fields,
+ group_index_names,
+ grouped_column_labels,
+ )
+
+
+class _DissolveResultLabels(typing.NamedTuple):
+ geometry_label: Label
+ attribute_labels: list
+ order_label: Label
+ geometry_name: Label
+ order_name: Label
+ column_label_names: list
+
+
+def _build_dissolve_result_labels(
+ internal,
+ geometry_label,
+ aggregation_specs,
+ result_column_levels,
+):
+ """Build non-colliding output labels for a dissolve result."""
+
+ result_geometry_label = geometry_label + ("",) * (
+ result_column_levels - len(geometry_label)
+ )
+ result_attribute_labels = [spec[3] for spec in aggregation_specs]
+ result_order_label_name = "__dissolve_group_order__"
+ result_order_label = (result_order_label_name,) + ("",) * (result_column_levels - 1)
+ result_labels = {result_geometry_label, *result_attribute_labels}
+ result_order_suffix = 0
+ while result_order_label in result_labels:
+ result_order_suffix += 1
+ result_order_label_name = f"__dissolve_group_order_{result_order_suffix}__"
+ result_order_label = (result_order_label_name,) + ("",) * (
+ result_column_levels - 1
+ )
+
+ result_geometry_name = (
+ result_geometry_label[0]
+ if len(result_geometry_label) == 1
+ else result_geometry_label
+ )
+ result_order_name = (
+ result_order_label[0] if len(result_order_label) == 1 else result_order_label
+ )
+ result_column_label_names = [
+ internal.column_label_names[0],
+ *([None] * (result_column_levels - 1)),
+ ]
+ return _DissolveResultLabels(
+ result_geometry_label,
+ result_attribute_labels,
+ result_order_label,
+ result_geometry_name,
+ result_order_name,
+ result_column_label_names,
+ )
+
+
+def _as_geodataframe_with_geometry(frame, geometry_name):
+ """Wrap a pandas-on-Spark result and restore its active geometry label."""
+
+ result = GeoDataFrame(frame)
+ result._geometry_column_name = geometry_name
+ return result
+
+
+def _dissolve_aggregation_expression(
+ column,
+ field,
+ aggregation,
+ natural_order,
+ column_label,
+):
+ """Build a validated native Spark aggregation for one attribute column."""
+
+ spark_type = field.spark_type
+ is_categorical = isinstance(field.dtype, pd.CategoricalDtype)
+ is_boolean = isinstance(spark_type, BooleanType)
+ is_numeric = isinstance(spark_type, NumericType)
+ is_float = isinstance(spark_type, (FloatType, DoubleType))
+ dtype_name = str(field.dtype) if is_categorical else spark_type.simpleString()
+
+ clean_column = (
+ F.when(F.isnan(column), F.lit(None)).otherwise(column) if is_float else column
+ )
+
+ if aggregation == "first":
+ return F.min_by(
+ clean_column,
+ F.when(clean_column.isNotNull(), natural_order),
+ )
+ if aggregation == "last":
+ return F.max_by(
+ clean_column,
+ F.when(clean_column.isNotNull(), natural_order),
+ )
+ if aggregation == "count":
+ return F.count(clean_column)
+ if aggregation == "nunique":
+ if is_categorical or not (
+ is_numeric or is_boolean or isinstance(spark_type, StringType)
+ ):
+ raise NotImplementedError(
+ "Sedona dissolve does not support aggregation "
+ f"{aggregation!r} for column {column_label!r} with data "
+ f"type {dtype_name!r}."
+ )
+ return F.countDistinct(clean_column)
+
+ if is_categorical or not (is_numeric or is_boolean):
+ raise NotImplementedError(
+ "Sedona dissolve supports aggregation "
+ f"{aggregation!r} only for numeric or boolean columns; "
+ f"column {column_label!r} has data type {dtype_name!r}."
+ )
+
+ numeric_column = clean_column.cast("double") if is_boolean else clean_column
+
+ if aggregation == "sum":
+ if is_boolean or isinstance(
+ spark_type,
+ (ByteType, ShortType, IntegerType, LongType),
+ ):
+ result = F.sum(numeric_column.cast("long")).cast("long")
+ identity = F.lit(0).cast("long")
+ elif isinstance(spark_type, FloatType):
+ result = F.sum(numeric_column).cast("float")
+ identity = F.lit(0).cast("float")
+ elif isinstance(spark_type, DoubleType):
+ result = F.sum(numeric_column).cast("double")
+ identity = F.lit(0).cast("double")
+ else:
+ result = F.sum(numeric_column)
+ identity = F.lit(0).cast(spark_type)
+ return F.coalesce(result, identity)
+
+ if aggregation == "mean":
+ result = F.avg(numeric_column)
+ elif aggregation == "median":
+ result = F.median(numeric_column)
+ elif aggregation == "std":
+ result = F.stddev_samp(numeric_column)
+ elif aggregation == "var":
+ result = F.var_samp(numeric_column)
+ elif aggregation == "min":
+ if is_boolean:
+ return F.min(clean_column.cast("integer")).cast("boolean")
+ return F.min(clean_column)
+ elif aggregation == "max":
+ if is_boolean:
+ return F.max(clean_column.cast("integer")).cast("boolean")
+ return F.max(clean_column)
+ else:
+ raise AssertionError(f"Unexpected dissolve aggregation: {aggregation}")
+
+ if isinstance(spark_type, FloatType):
+ return result.cast("float")
+ return result
+
+
class GeoDataFrame(GeoFrame, pspd.DataFrame):
"""
A pandas-on-Spark DataFrame for geospatial data with geometry columns.
@@ -595,6 +970,7 @@ class GeoDataFrame(GeoFrame, pspd.DataFrame):
if new_series:
# Note: This casts GeoSeries back into pspd.Series, so we lose any metadata that's not serialized.
frame[geo_column_name] = level
+ object.__setattr__(frame, "_empty_crs_source", level)
if not inplace:
return frame
@@ -1376,6 +1752,390 @@ class GeoDataFrame(GeoFrame, pspd.DataFrame):
"""
return self.to_geopandas().plot(*args, **kwargs)
+ def dissolve(
+ self,
+ by=None,
+ aggfunc="first",
+ as_index: bool = True,
+ level=None,
+ sort: bool = True,
+ observed: bool = False,
+ dropna: bool = True,
+ method: Literal["unary", "coverage", "disjoint_subset"] = "unary",
+ grid_size=None,
+ **kwargs,
+ ) -> GeoDataFrame:
+ """Dissolve geometries within groups using distributed aggregation.
+
+ Geometry unions are evaluated by Sedona's ``ST_Union_Aggr`` aggregate.
+ Attribute columns use validated native Spark aggregate expressions and
+ therefore remain distributed as well.
+
+ Parameters
+ ----------
+ by : column label or list of column labels, default None
+ Columns defining the groups. ``None`` dissolves all rows into one
+ group. Arbitrary driver-side grouping vectors are not supported.
+ aggfunc : str, callable, list, or dict, default "first"
+ Aggregation(s) for non-geometry columns. ``first``, ``last``, and
+ ``count`` support every Spark data type. ``nunique`` supports
+ numeric, boolean, and string columns. ``min``, ``max``, ``sum``,
+ ``mean``, ``median``, ``std``, and ``var`` support numeric and
+ boolean columns. String ``sum`` and every ``prod`` aggregation are
+ not supported.
+ as_index : bool, default True
+ Place grouping columns in the result index.
+ level : int, name, or sequence, default None
+ Group by one or more input index levels. When supplied, ``level``
+ takes precedence over ``by``, matching pandas.
+ sort : bool, default True
+ Sort group keys. With ``False``, groups follow first occurrence.
+ Preserving that order still requires a distributed sort by each
+ group's first source-row position.
+ observed : bool, default False
+ For categorical groupers, ``True`` returns observed groups.
+ Materializing unobserved categorical combinations is unsupported.
+ dropna : bool, default True
+ Drop null grouping keys when true.
+ method : {"unary"}, default "unary"
+ Union algorithm. Sedona currently supports only the robust unary
+ union for this API.
+ grid_size : None, default None
+ Fixed-precision union is not currently supported.
+ **kwargs
+ ``numeric_only`` is supported for non-dict aggregations.
+
+ Returns
+ -------
+ GeoDataFrame
+ A distributed GeoDataFrame with one row per group.
+
+ Examples
+ --------
+ >>> from sedona.spark.geopandas import GeoDataFrame
+ >>> from shapely.geometry import Point
+ >>> gdf = GeoDataFrame(
+ ... {
+ ... "zone": ["a", "a", "b"],
+ ... "value": [1, 2, 3],
+ ... "geometry": [Point(0, 0), Point(1, 1), Point(5, 5)],
+ ... },
+ ... crs="EPSG:4326",
+ ... )
+ >>> gdf.dissolve("zone", aggfunc="sum").sort_index()
+ geometry value
+ zone
+ a MULTIPOINT ((0 0), (1 1)) 3
+ b POINT (5 5) 3
+
+ Notes
+ -----
+ Python row UDFs are not used. Callable aliases are limited to built-in
+ ``min``, ``max``, and ``sum``, plus NumPy ``amin``, ``amax``, ``min``,
+ ``max``, ``sum``, ``mean``, ``median``, ``std``, and ``var``.
+ ``first`` and ``last`` follow source row order and skip null and NaN
+ values. Numeric and boolean ``sum`` use pandas' zero identity for an
+ all-null group; boolean sums are returned as integers and boolean
+ statistical aggregations as floating-point values.
+
+ GeoPandas flattens multiple aggregation labels into a one-level object
+ index containing tuples. pandas-on-Spark cannot represent tuple-valued
+ labels in a one-level column index, so Sedona keeps those results as a
+ two-level ``MultiIndex`` and uses ``(geometry_name, "")`` for the
+ active geometry label.
+ """
+ if method != "unary":
+ raise NotImplementedError(
+ "Sedona dissolve currently supports only method='unary'."
+ )
+ if grid_size is not None:
+ raise NotImplementedError(
+ "Sedona dissolve does not support the grid_size argument."
+ )
+
+ unsupported_kwargs = set(kwargs) - {"numeric_only"}
+ if unsupported_kwargs:
+ unsupported = ", ".join(sorted(unsupported_kwargs))
+ raise NotImplementedError(
+ f"Sedona dissolve does not support aggregation keyword(s): {unsupported}."
+ )
+ numeric_only = kwargs.get("numeric_only", False)
+ if not isinstance(numeric_only, (bool, np.bool_)):
+ raise TypeError("numeric_only must be a boolean")
+ if isinstance(aggfunc, dict) and "numeric_only" in kwargs:
+ raise NotImplementedError(
+ "Sedona dissolve supports numeric_only only with non-dict "
+ "aggregations."
+ )
+
+ internal = self._internal.resolved_copy
+ if internal.column_labels_level != 1:
+ raise NotImplementedError(
+ "Sedona dissolve does not yet support MultiIndex columns."
+ )
+
+ geometry_label = self.geometry._column_label
+
+ groupers = _resolve_dissolve_groupers(
+ self,
+ internal,
+ geometry_label,
+ by,
+ level,
+ observed,
+ )
+ group_expressions = groupers.expressions
+ group_fields = groupers.fields
+ group_index_names = groupers.index_names
+ grouped_column_labels = groupers.column_labels
+
+ normalized_aggfunc = _normalize_dissolve_aggfunc(aggfunc)
+ available_attribute_labels = [
+ label for label in internal.column_labels if label != geometry_label
+ ]
+ if isinstance(normalized_aggfunc, dict):
+ if not normalized_aggfunc:
+ raise ValueError("No objects to concatenate")
+ missing_keys = [
+ key
+ for key in normalized_aggfunc
+ if (key,) not in available_attribute_labels
+ ]
+ if missing_keys:
+ missing = ", ".join(repr(key) for key in missing_keys)
+ raise KeyError(f"Column(s) [{missing}] do not exist")
+ # A grouping column is excluded from a normal aggregation, but a
+ # dict can request it explicitly, as pandas GroupBy.agg allows.
+ attribute_labels = available_attribute_labels
+ else:
+ attribute_labels = [
+ label
+ for label in available_attribute_labels
+ if label not in grouped_column_labels
+ ]
+ if numeric_only and not isinstance(aggfunc, dict):
+ attribute_labels = [
+ label
+ for label in attribute_labels
+ if pd.api.types.is_numeric_dtype(internal.field_for(label).dtype)
+ ]
+
+ aggregation_specs = []
+ if isinstance(normalized_aggfunc, dict):
+ result_column_levels = (
+ 2
+ if any(
+ isinstance(functions, list)
+ for functions in normalized_aggfunc.values()
+ )
+ else 1
+ )
+ for key, functions in normalized_aggfunc.items():
+ source_label = (key,)
+ field = internal.field_for(source_label)
+ function_names = (
+ functions if isinstance(functions, list) else [functions]
+ )
+ for function_name in function_names:
+ result_label = (
+ (key, function_name)
+ if result_column_levels == 2
+ else source_label
+ )
+ aggregation_specs.append(
+ (source_label, field, function_name, result_label)
+ )
+ else:
+ function_names = (
+ normalized_aggfunc
+ if isinstance(normalized_aggfunc, list)
+ else [normalized_aggfunc]
+ )
+ if not function_names:
+ raise ValueError("No objects to concatenate")
+ result_column_levels = 2 if isinstance(normalized_aggfunc, list) else 1
+ for source_label in attribute_labels:
+ field = internal.field_for(source_label)
+ for function_name in function_names:
+ result_label = (
+ (source_label[0], function_name)
+ if result_column_levels == 2
+ else source_label
+ )
+ aggregation_specs.append(
+ (source_label, field, function_name, result_label)
+ )
+
+ if isinstance(normalized_aggfunc, list) and not aggregation_specs:
+ raise ValueError("No objects to concatenate")
+ if isinstance(normalized_aggfunc, dict) and not aggregation_specs:
+ # GeoPandas treats a non-empty dict containing only empty
+ # function lists as a geometry-only aggregation.
+ result_column_levels = 1
+
+ source_sdf = internal.spark_frame
+ group_column_names = [
+ SPARK_INDEX_NAME_FORMAT(position)
+ for position in range(len(group_expressions))
+ ]
+ geometry_input_name = "__dissolve_geometry_input__"
+ order_input_name = "__dissolve_order_input__"
+ geometry_output_name = "__dissolve_geometry_output__"
+ order_output_spark_name = "__dissolve_group_order__"
+
+ attribute_input_names = {}
+ attribute_input_columns = []
+ for source_label, _, _, _ in aggregation_specs:
+ if source_label not in attribute_input_names:
+ input_name = (
+ f"__dissolve_attribute_input_{len(attribute_input_names)}__"
+ )
+ attribute_input_names[source_label] = input_name
+ attribute_input_columns.append(
+ internal.spark_column_for(source_label).alias(input_name)
+ )
+
+ aggregation_input = source_sdf.select(
+ *[
+ expression.alias(group_name)
+ for expression, group_name in zip(
+ group_expressions,
+ group_column_names,
+ )
+ ],
+ internal.spark_column_for(geometry_label).alias(geometry_input_name),
+ scol_for(source_sdf, NATURAL_ORDER_COLUMN_NAME).alias(order_input_name),
+ *attribute_input_columns,
+ )
+
+ attribute_output_names = [
+ f"__dissolve_attribute_{position}__"
+ for position in range(len(aggregation_specs))
+ ]
+ attribute_aggregations = [
+ _dissolve_aggregation_expression(
+ F.col(attribute_input_names[source_label]),
+ field,
+ function_name,
+ F.col(order_input_name),
+ source_label[0],
+ ).alias(output_name)
+ for (
+ source_label,
+ field,
+ function_name,
+ _,
+ ), output_name in zip(aggregation_specs, attribute_output_names)
+ ]
+
+ # CRS lookup is eager. Keep it after all aggregation validation so
+ # unsupported function/dtype combinations fail before Spark executes.
+ crs = self.crs
+ srid = crs.to_epsg() if crs is not None else 0
+ geometry_union = sta.ST_Union_Aggr(F.col(geometry_input_name))
+ if hasattr(gpd.GeoSeries, "union_all"):
+ # GeoPandas 1.0 changed an all-null union from None to an empty
+ # GeometryCollection. Preserve its CRS in that representation.
+ empty_geometry = stc.ST_GeomFromWKT(
+ F.lit("GEOMETRYCOLLECTION EMPTY"),
+ srid or 0,
+ )
+ geometry_union = F.coalesce(geometry_union, empty_geometry)
+ aggregated_sdf = aggregation_input.groupBy(*group_column_names).agg(
+ geometry_union.alias(geometry_output_name),
+ F.min(F.col(order_input_name)).alias(order_output_spark_name),
+ *attribute_aggregations,
+ )
+ if dropna:
+ aggregated_sdf = aggregated_sdf.dropna(subset=group_column_names)
+
+ result_labels = _build_dissolve_result_labels(
+ internal,
+ geometry_label,
+ aggregation_specs,
+ result_column_levels,
+ )
+
+ result_internal = InternalFrame(
+ spark_frame=aggregated_sdf,
+ index_spark_columns=[
+ scol_for(aggregated_sdf, name) for name in group_column_names
+ ],
+ index_names=group_index_names,
+ index_fields=[
+ (
+ field.copy(name=name)
+ if field is not None
+ else InternalField.from_struct_field(aggregated_sdf.schema[name])
+ )
+ for field, name in zip(group_fields, group_column_names)
+ ],
+ column_labels=[
+ result_labels.geometry_label,
+ result_labels.order_label,
+ *result_labels.attribute_labels,
+ ],
+ data_spark_columns=[
+ scol_for(aggregated_sdf, geometry_output_name),
+ scol_for(aggregated_sdf, order_output_spark_name),
+ *[scol_for(aggregated_sdf, name) for name in attribute_output_names],
+ ],
+ data_fields=[
+ InternalField(
+ np.dtype("object"),
+ aggregated_sdf.schema[geometry_output_name],
+ ),
+ InternalField.from_struct_field(
+ aggregated_sdf.schema[order_output_spark_name]
+ ),
+ *[
+ (
+ InternalField(field.dtype, aggregated_sdf.schema[name])
+ if function_name in {"first", "last", "min", "max"}
+ else InternalField.from_struct_field(
+ aggregated_sdf.schema[name]
+ )
+ )
+ for (
+ _,
+ field,
+ function_name,
+ _,
+ ), name in zip(aggregation_specs, attribute_output_names)
+ ],
+ ],
+ column_label_names=result_labels.column_label_names,
+ )
+ aggregated = _as_geodataframe_with_geometry(
+ PandasOnSparkDataFrame(result_internal),
+ result_labels.geometry_name,
+ )
+
+ if sort:
+ aggregated = _as_geodataframe_with_geometry(
+ aggregated.sort_index(na_position="last"),
+ result_labels.geometry_name,
+ )
+ else:
+ aggregated = _as_geodataframe_with_geometry(
+ aggregated.sort_values(result_labels.order_name),
+ result_labels.geometry_name,
+ )
+
+ aggregated = _as_geodataframe_with_geometry(
+ aggregated.drop(columns=[result_labels.order_name]),
+ result_labels.geometry_name,
+ )
+
+ if not as_index:
+ aggregated = _as_geodataframe_with_geometry(
+ aggregated.reset_index(),
+ result_labels.geometry_name,
+ )
+
+ object.__setattr__(aggregated, "_empty_crs_source", self.geometry)
+ return aggregated
+
# ============================================================================
# SPATIAL OPERATIONS
# ============================================================================
diff --git a/python/sedona/spark/geopandas/geoseries.py b/python/sedona/spark/geopandas/geoseries.py
index ce5fd45f5a8..138f6e584c1 100644
--- a/python/sedona/spark/geopandas/geoseries.py
+++ b/python/sedona/spark/geopandas/geoseries.py
@@ -861,7 +861,12 @@ class GeoSeries(GeoFrame, pspd.Series):
Same as `to_geopandas()`, without issuing the advice log for internal usage.
"""
pd_series = self._to_internal_pandas()
- return gpd.GeoSeries(pd_series, crs=self.crs)
+ return gpd.GeoSeries(
+ pd_series.array,
+ index=pd_series.index,
+ name=pd_series.name,
+ crs=self.crs,
+ )
def to_spark_pandas(self) -> pspd.Series:
return pspd.Series(pspd.DataFrame(self._psdf._internal))
diff --git a/python/sedona/spark/geopandas/tools/__init__.py b/python/sedona/spark/geopandas/tools/__init__.py
index e154327f7da..0faa8fb7d6b 100644
--- a/python/sedona/spark/geopandas/tools/__init__.py
+++ b/python/sedona/spark/geopandas/tools/__init__.py
@@ -15,10 +15,12 @@
# specific language governing permissions and limitations
# under the License.
-from .sjoin import sjoin
from .clip import clip
+from .collect import collect
+from .sjoin import sjoin
__all__ = [
"clip",
+ "collect",
"sjoin",
]
diff --git a/python/sedona/spark/geopandas/tools/collect.py b/python/sedona/spark/geopandas/tools/collect.py
new file mode 100644
index 00000000000..b641b60517c
--- /dev/null
+++ b/python/sedona/spark/geopandas/tools/collect.py
@@ -0,0 +1,146 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import geopandas as gpd
+import shapely
+from packaging.version import parse as parse_version
+from pyspark.sql import functions as F
+
+from sedona.spark.sql import st_aggregates as sta
+from sedona.spark.sql import st_constructors as stc
+from sedona.spark.sql import st_functions as stf
+
+SHAPELY_LT_20 = parse_version(shapely.__version__) < parse_version("2.0.0")
+
+
+def collect(x, multi=False):
+ """Collect single-part geometries into their multipart counterpart.
+
+ A Sedona :class:`~sedona.spark.geopandas.GeoSeries` is aggregated on
+ executors with ``ST_Collect_Agg``. One aggregate action materializes only
+ the metadata and single geometry required by this scalar-returning API on
+ the driver. Local Shapely and GeoPandas inputs retain GeoPandas' behavior.
+
+ Parameters
+ ----------
+ x : GeoSeries, iterable, or Shapely geometry
+ Homogeneous geometries to collect.
+ multi : bool, default False
+ Force a singleton single-part geometry into its multipart type.
+
+ Returns
+ -------
+ shapely.geometry.base.BaseGeometry
+ A singleton geometry or its collected multipart geometry.
+
+ Raises
+ ------
+ ValueError
+ If geometry types differ, or multiple multipart geometries are passed.
+
+ Examples
+ --------
+ >>> from shapely.geometry import Point
+ >>> from sedona.spark.geopandas import GeoSeries
+ >>> from sedona.spark.geopandas.tools import collect
+ >>> collect(GeoSeries([Point(0, 0), Point(1, 1)]))
+ <MULTIPOINT ((0 0), (1 1))>
+ >>> collect(Point(0, 0), multi=True)
+ <MULTIPOINT ((0 0))>
+ """
+ from sedona.spark.geopandas import GeoSeries
+
+ if not isinstance(x, GeoSeries):
+ return gpd.tools.collect(x, multi=multi)
+
+ geometry = x.spark.column
+ geometry_type = stf.ST_GeometryType(geometry)
+ geometry_is_empty = stf.ST_IsEmpty(geometry)
+ if SHAPELY_LT_20:
+ # Shapely 1 reports every empty geometry as GeometryCollection,
+ # regardless of whether the serializer retains its original family.
+ geometry_type = F.when(
+ geometry_is_empty,
+ F.lit("ST_GeometryCollection"),
+ ).otherwise(geometry_type)
+ non_empty_geometry = F.when(~geometry_is_empty, geometry)
+ first_geometry_type = F.first(geometry_type, ignorenulls=True)
+ empty_multipolygon = stc.ST_GeomFromWKT(
+ F.lit("MULTIPOLYGON EMPTY"),
+ F.first(stf.ST_SRID(geometry), ignorenulls=True),
+ )
+ collected_geometry = F.coalesce(
+ sta.ST_Collect_Agg(non_empty_geometry),
+ F.when(
+ first_geometry_type == F.lit("ST_Polygon"),
+ empty_multipolygon,
+ ),
+ )
+ metadata = x._internal.spark_frame.agg(
+ F.count(F.lit(1)).alias("__collect_count__"),
+ F.count(geometry).alias("__collect_non_null_count__"),
+ F.count(non_empty_geometry).alias("__collect_non_empty_count__"),
+ F.countDistinct(geometry_type).alias("__collect_type_count__"),
+ first_geometry_type.alias("__collect_type__"),
+ F.first(geometry, ignorenulls=True).alias("__collect_single_geometry__"),
+ collected_geometry.alias("__collect_geometry__"),
+ ).first()
+
+ count = metadata["__collect_count__"]
+ non_null_count = metadata["__collect_non_null_count__"]
+ if count == 0:
+ raise IndexError("list index out of range")
+ if non_null_count != count:
+ raise AttributeError("'NoneType' object has no attribute 'geom_type'")
+ if metadata["__collect_type_count__"] != 1:
+ raise ValueError("Geometry type must be homogeneous")
+
+ geometry_type_name = metadata["__collect_type__"]
+ if geometry_type_name.startswith("ST_"):
+ geometry_type_name = geometry_type_name[3:]
+
+ is_multi = geometry_type_name.startswith("Multi")
+ if count > 1 and is_multi:
+ raise ValueError(
+ f"Cannot collect {geometry_type_name}. Must have single geometries"
+ )
+
+ if count == 1 and (is_multi or not multi):
+ return metadata["__collect_single_geometry__"]
+
+ if geometry_type_name not in {"Point", "LineString", "Polygon"}:
+ raise KeyError(geometry_type_name)
+
+ non_empty_count = metadata["__collect_non_empty_count__"]
+ has_empty = non_empty_count != count
+ if has_empty and geometry_type_name in {
+ "Point",
+ "LineString",
+ }:
+ # EmptyPartError was added after Shapely 1.7.0, Sedona's supported
+ # dependency floor. Keep importing this module safe on that version.
+ try:
+ from shapely.errors import EmptyPartError
+ except ImportError:
+ raise ValueError(
+ f"Can't create Multi{geometry_type_name} with empty component"
+ ) from None
+ raise EmptyPartError(
+ f"Can't create Multi{geometry_type_name} with empty component"
+ )
+
+ return metadata["__collect_geometry__"]
diff --git a/python/tests/geopandas/test_geometry_aggregation.py b/python/tests/geopandas/test_geometry_aggregation.py
new file mode 100644
index 00000000000..a06e0728130
--- /dev/null
+++ b/python/tests/geopandas/test_geometry_aggregation.py
@@ -0,0 +1,604 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import geopandas as gpd
+import numpy as np
+import pandas as pd
+import pytest
+import pyspark.pandas as ps
+import shapely
+from packaging.version import parse as parse_version
+from pyspark.sql import functions as F
+
+try:
+ from shapely.errors import EmptyPartError
+except ImportError:
+ EmptyPartError = ValueError
+from shapely.geometry import (
+ GeometryCollection,
+ LineString,
+ MultiPoint,
+ Point,
+ Polygon,
+)
+
+from sedona.spark.geopandas import GeoDataFrame, GeoSeries
+from sedona.spark.geopandas.tools import collect
+from sedona.spark.sql import st_functions as stf
+from tests.geopandas.test_geopandas_base import TestGeopandasBase
+
+SHAPELY_GE_20 = parse_version(shapely.__version__) >= parse_version("2.0.0")
+GEOPANDAS_HAS_UNION_ALL = hasattr(gpd.GeoSeries, "union_all")
+
+
+class TestGeometryAggregation(TestGeopandasBase):
+ def test_dissolve_grouped_matches_geopandas(self):
+ data = {
+ "zone": ["b", "a", "b", None],
+ "label": ["first-b", "only-a", "second-b", "missing"],
+ "value": [1, 2, 3, 4],
+ "shape": [Point(0, 0), Point(5, 5), Point(1, 1), None],
+ }
+ expected_source = gpd.GeoDataFrame(data, geometry="shape", crs="EPSG:3857")
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ source = GeoDataFrame(expected_source)
+ result = source.dissolve(
+ "zone", aggfunc={"label": "first", "value": "sum"}, dropna=False
+ )
+ spark_frame = result._internal.spark_frame
+ if hasattr(spark_frame, "_jdf"):
+ plan = spark_frame._jdf.queryExecution().executedPlan().toString()
+ assert "BatchEvalPython" not in plan
+ assert "ArrowEvalPython" not in plan
+ expected = expected_source.dissolve(
+ "zone",
+ aggfunc={"label": "first", "value": "sum"},
+ dropna=False,
+ )
+
+ self.check_sgpd_df_equals_gpd_df(result, expected)
+ assert result.active_geometry_name == "shape"
+ assert result.crs == expected.crs
+ collected = result.to_geopandas()
+ null_group = collected[collected.index.isna()].iloc[0]
+ assert null_group["label"] == "missing"
+ if GEOPANDAS_HAS_UNION_ALL:
+ assert null_group["shape"].is_empty
+ else:
+ assert null_group["shape"] is None
+
+ srids = (
+ result.geometry._internal.spark_frame.select(
+ stf.ST_SRID(result.geometry.spark.column).alias("srid")
+ )
+ .distinct()
+ .collect()
+ )
+ expected_srids = {3857} if GEOPANDAS_HAS_UNION_ALL else {3857, None}
+ assert {row.srid for row in srids} == expected_srids
+
+ def test_dissolve_all_null_geometry_matches_geopandas_and_preserves_crs(self):
+ expected_source = gpd.GeoDataFrame(
+ {
+ "zone": ["a", "a"],
+ "geometry": [None, None],
+ },
+ crs="EPSG:4326",
+ )
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ source = GeoDataFrame(expected_source)
+
+ assert source.crs == expected_source.crs
+ result = source.dissolve("zone")
+ expected = expected_source.dissolve("zone")
+
+ self.check_sgpd_df_equals_gpd_df(result, expected)
+ assert result.crs == expected.crs
+ srids = result.geometry._internal.spark_frame.select(
+ stf.ST_SRID(result.geometry.spark.column).alias("srid")
+ ).collect()
+ expected_srid = 4326 if GEOPANDAS_HAS_UNION_ALL else None
+ assert [row.srid for row in srids] == [expected_srid]
+
+ def test_dissolve_series_grouper_retains_data_column(self):
+ local = gpd.GeoDataFrame(
+ {
+ "zone": ["a", "a", "b"],
+ "label": ["first-a", "second-a", "only-b"],
+ "value": [1, 2, 3],
+ "geometry": [Point(0, 0), Point(1, 1), Point(2, 2)],
+ },
+ crs="EPSG:4326",
+ )
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ source = GeoDataFrame(local)
+
+ label_result = source.dissolve(by="zone")
+ series_result = source.dissolve(by=source["zone"])
+ expected = local.dissolve(by=local["zone"])
+
+ assert "zone" not in label_result.columns
+ assert list(series_result.columns) == [
+ "geometry",
+ "zone",
+ "label",
+ "value",
+ ]
+ collected = series_result.to_geopandas()
+ assert collected.index.name == expected.index.name == "zone"
+ assert collected.geometry.name == "geometry"
+ assert collected.crs == expected.crs == source.crs
+ assert collected.loc["a", "zone"] == "a"
+ assert collected.loc["a", "label"] == "first-a"
+ assert collected.loc["a", "value"] == 1
+ self.check_sgpd_df_equals_gpd_df(series_result, expected)
+
+ def test_dissolve_all_rows_and_as_index_false(self):
+ data = {
+ "label": ["first", "second"],
+ "value": [2, 3],
+ "geometry": [Point(0, 0), Point(1, 1)],
+ }
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ source = GeoDataFrame(data, crs="EPSG:4326")
+ result = source.dissolve(
+ aggfunc={"label": "first", "value": "sum"},
+ as_index=False,
+ )
+
+ assert list(result.columns) == ["index", "geometry", "label", "value"]
+ row = result.to_geopandas().iloc[0]
+ assert row["index"] == 0
+ assert row["label"] == "first"
+ assert row["value"] == 5
+ assert row["geometry"].equals(MultiPoint([(0, 0), (1, 1)]))
+ assert result.crs == source.crs
+ assert result["index"].dtype == np.dtype("int64")
+
+ def test_dissolve_level_multikey_and_sort(self):
+ index = pd.MultiIndex.from_tuples(
+ [("z", 2), ("a", 1), ("z", 1)],
+ names=["letter", "number"],
+ )
+ source = gpd.GeoDataFrame(
+ {
+ "kind": ["q", "q", "r"],
+ "value": [1, 2, 3],
+ "geometry": [Point(0, 0), Point(1, 1), Point(2, 2)],
+ },
+ index=index,
+ crs="EPSG:4326",
+ )
+
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ distributed = GeoDataFrame(source)
+
+ level_result = distributed.dissolve(level="letter")
+ level_expected = source.dissolve(level="letter")
+ self.check_sgpd_df_equals_gpd_df(level_result, level_expected)
+ assert level_result.index.names == ["letter"]
+
+ multikey_result = distributed.dissolve(
+ by=["kind", "value"],
+ sort=False,
+ )
+ multikey_expected = source.dissolve(
+ by=["kind", "value"],
+ sort=False,
+ )
+ self.check_sgpd_df_equals_gpd_df(multikey_result, multikey_expected)
+ assert multikey_result.index.names == ["kind", "value"]
+
+ def test_dissolve_multiple_aggregations_including_grouping_column(self):
+ local = gpd.GeoDataFrame(
+ {
+ "zone": ["a", "a", "b"],
+ "value": [1, 3, 2],
+ "label": ["x", "y", "z"],
+ "geometry": [Point(0, 0), Point(1, 1), Point(2, 2)],
+ }
+ )
+ local.columns.name = "attributes"
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ source = GeoDataFrame(local)
+ result = source.dissolve(
+ "zone",
+ aggfunc={
+ "zone": "first",
+ "value": ("sum", "max"),
+ "label": "first",
+ },
+ )
+ collected = result.to_geopandas()
+
+ assert isinstance(result.columns, pd.MultiIndex)
+ assert result.columns.names == ["attributes", None]
+ assert result.active_geometry_name == ("geometry", "")
+ assert collected.loc["a", ("zone", "first")] == "a"
+ assert collected.loc["a", ("value", "sum")] == 4
+ assert collected.loc["a", ("value", "max")] == 3
+ assert collected.loc["a", ("label", "first")] == "x"
+
+ def test_dissolve_first_last_skip_nulls_in_source_order(self):
+ source = GeoDataFrame(
+ {
+ "zone": ["a"] * 6 + ["b"] * 2,
+ "label": [
+ None,
+ "first",
+ "middle",
+ None,
+ "last",
+ None,
+ None,
+ None,
+ ],
+ "value": [
+ np.nan,
+ 1.0,
+ 2.0,
+ np.nan,
+ 3.0,
+ np.nan,
+ np.nan,
+ np.nan,
+ ],
+ "geometry": [Point(i, i) for i in range(8)],
+ }
+ )
+ distributed_result = source.dissolve(
+ "zone",
+ aggfunc={
+ "label": ["first", "last", "count", "nunique"],
+ "value": ["first", "last", "count", "nunique"],
+ },
+ )
+ spark_frame = distributed_result._internal.spark_frame
+ if hasattr(spark_frame, "_jdf"):
+ plan = spark_frame._jdf.queryExecution().analyzed().toString().lower()
+ assert "min_by" in plan
+ assert "max_by" in plan
+ result = distributed_result.to_geopandas()
+
+ assert result.loc["a", ("label", "first")] == "first"
+ assert result.loc["a", ("label", "last")] == "last"
+ assert result.loc["a", ("label", "count")] == 3
+ assert result.loc["a", ("label", "nunique")] == 3
+ assert result.loc["a", ("value", "first")] == 1.0
+ assert result.loc["a", ("value", "last")] == 3.0
+ assert result.loc["a", ("value", "count")] == 3
+ assert result.loc["a", ("value", "nunique")] == 3
+ assert result.loc["b", ("label", "first")] is None
+ assert result.loc["b", ("label", "last")] is None
+ assert result.loc["b", ("label", "count")] == 0
+ assert result.loc["b", ("label", "nunique")] == 0
+ assert pd.isna(result.loc["b", ("value", "first")])
+ assert pd.isna(result.loc["b", ("value", "last")])
+
+ def test_dissolve_numeric_boolean_aggregation_semantics(self):
+ local = gpd.GeoDataFrame(
+ {
+ "zone": ["a", "a", "b", "b"],
+ "integer": [1, 2, 3, 4],
+ "number": [1.5, 2.5, np.nan, np.nan],
+ "flag": pd.Series([True, False, None, None], dtype="boolean"),
+ "geometry": [Point(i, i) for i in range(4)],
+ }
+ )
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ source = GeoDataFrame(local)
+
+ result = source.dissolve(
+ "zone",
+ aggfunc={
+ "integer": [np.sum, np.mean],
+ "number": "sum",
+ "flag": ["sum", "mean", "median", "std", "var", "min", "max"],
+ },
+ ).to_geopandas()
+
+ assert result.loc["a", ("integer", "sum")] == 3
+ assert result.loc["a", ("integer", "mean")] == 1.5
+ assert result[("integer", "sum")].dtype == np.dtype("int64")
+ assert result.loc["b", ("number", "sum")] == 0.0
+ assert result.loc["a", ("flag", "sum")] == 1
+ assert result.loc["b", ("flag", "sum")] == 0
+ assert result[("flag", "sum")].dtype == np.dtype("int64")
+ assert result.loc["a", ("flag", "mean")] == 0.5
+ assert result.loc["a", ("flag", "median")] == 0.5
+ assert result.loc["a", ("flag", "std")] == pytest.approx(2**-0.5)
+ assert result.loc["a", ("flag", "var")] == 0.5
+ assert not bool(result.loc["a", ("flag", "min")])
+ assert bool(result.loc["a", ("flag", "max")])
+ for function_name in ["mean", "median", "std", "var"]:
+ assert result[("flag", function_name)].dtype == np.dtype("float64")
+
+ def test_dissolve_empty_preserves_crs(self):
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ source = GeoDataFrame(
+ gpd.GeoDataFrame(
+ {
+ "zone": pd.Series(dtype="object"),
+ "geometry": gpd.GeoSeries([], crs="EPSG:3857"),
+ },
+ geometry="geometry",
+ crs="EPSG:3857",
+ )
+ )
+ assert source.crs == "EPSG:3857"
+
+ result = source.dissolve("zone")
+ assert result.to_geopandas().empty
+ assert result.crs == source.crs
+ assert result.active_geometry_name == "geometry"
+
+ empty_geometry = result.geometry
+ empty_geometry.set_crs(None, inplace=True)
+ assert empty_geometry.crs is None
+
+ def test_dissolve_validation(self):
+ source = GeoDataFrame({"zone": ["a"], "geometry": [Point(0, 0)]})
+
+ with pytest.raises(NotImplementedError, match="method='unary'"):
+ source.dissolve("zone", method="coverage")
+ with pytest.raises(NotImplementedError, match="grid_size"):
+ source.dissolve("zone", grid_size=1)
+ with pytest.raises(NotImplementedError, match="known built-in"):
+ source.dissolve("zone", aggfunc=lambda values: values.iloc[0])
+ with pytest.raises(NotImplementedError, match="grouping vectors"):
+ source.dissolve(["a"])
+ with pytest.raises(NotImplementedError, match="numeric_only"):
+ source.dissolve(
+ "zone",
+ aggfunc={"zone": "first"},
+ numeric_only=True,
+ )
+ with pytest.raises(NotImplementedError, match="prod aggregation"):
+ source.dissolve("zone", aggfunc="prod")
+
+ strings = GeoDataFrame(
+ {
+ "zone": ["a", "a"],
+ "label": ["x", "y"],
+ "geometry": [Point(0, 0), Point(1, 1)],
+ }
+ )
+ for aggregation in ["min", "max", "sum", "mean", "median", "std", "var"]:
+ with pytest.raises(
+ NotImplementedError,
+ match=rf"'{aggregation}'.*column 'label'.*'string'",
+ ):
+ strings.dissolve("zone", aggfunc=aggregation)
+
+ def sum(values):
+ return values.sum()
+
+ with pytest.raises(NotImplementedError, match="known built-in"):
+ source.dissolve("zone", aggfunc=sum)
+
+ geometry_only = GeoDataFrame({"geometry": [Point(0, 0)]})
+ assert list(geometry_only.dissolve().columns) == ["geometry"]
+ with pytest.raises(ValueError, match="No objects to concatenate"):
+ geometry_only.dissolve(aggfunc=["first"])
+
+ empty_dict_functions = GeoDataFrame(
+ {"value": [1], "geometry": [Point(0, 0)]}
+ ).dissolve(aggfunc={"value": []})
+ assert list(empty_dict_functions.columns) == ["geometry"]
+
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ categorical = GeoDataFrame(
+ gpd.GeoDataFrame(
+ {
+ "zone": pd.Categorical(["a"], categories=["a", "b"]),
+ "geometry": [Point(0, 0)],
+ }
+ )
+ )
+ with pytest.raises(NotImplementedError, match="observed=True"):
+ categorical.dissolve("zone")
+
+ categorical_values = gpd.GeoDataFrame(
+ {
+ "zone": ["a", "a"],
+ "category": pd.Categorical(["x", None]),
+ "geometry": [Point(0, 0), Point(1, 1)],
+ }
+ )
+ with ps.option_context("compute.ops_on_diff_frames", True):
+ distributed_categories = GeoDataFrame(categorical_values)
+ category_result = distributed_categories.dissolve(
+ "zone",
+ aggfunc={"category": "first"},
+ ).to_geopandas()
+ assert category_result.loc["a", "category"] == "x"
+ assert isinstance(category_result["category"].dtype, pd.CategoricalDtype)
+ with pytest.raises(
+ NotImplementedError,
+ match="'nunique'.*'category'",
+ ):
+ distributed_categories.dissolve(
+ "zone",
+ aggfunc={"category": "nunique"},
+ )
+
+ def test_collect_scalar_and_distributed_singletons(self):
+ point = Point(0, 0)
+ assert collect(point) is point
+ assert collect(point, multi=True).equals(MultiPoint([(0, 0)]))
+
+ assert collect(GeoSeries([point])).equals(point)
+ assert collect(GeoSeries([point]), multi=True).equals(MultiPoint([(0, 0)]))
+
+ multi_point = MultiPoint([(0, 0), (1, 1)])
+ assert collect(GeoSeries([multi_point]), multi=True).equals(multi_point)
+
+ @pytest.mark.parametrize(
+ "geometries, crs, expected_srid",
+ [
+ ([Point(0, 0), Point(1, 1)], None, 0),
+ pytest.param(
+ [
+ Polygon(),
+ Polygon([(0, 0), (1, 0), (0, 1)]),
+ ],
+ None,
+ 0,
+ marks=pytest.mark.skipif(
+ not SHAPELY_GE_20,
+ reason="Shapely 1 does not retain typed empty geometries",
+ ),
+ ),
+ pytest.param(
+ [Polygon(), Polygon()],
+ "EPSG:4326",
+ 4326,
+ marks=pytest.mark.skipif(
+ not SHAPELY_GE_20,
+ reason="Shapely 1 does not retain typed empty geometries",
+ ),
+ ),
+ ],
+ )
+ def test_collect_uses_one_spark_action(
+ self,
+ monkeypatch,
+ geometries,
+ crs,
+ expected_srid,
+ ):
+ first_calls = 0
+ result_srids = []
+ series = GeoSeries(geometries, crs=crs)
+ spark_frame_type = type(series._internal.spark_frame)
+ original_first = spark_frame_type.first
+
+ def count_first(frame):
+ nonlocal first_calls
+ first_calls += 1
+ enriched = frame.select(
+ "*",
+ stf.ST_SRID(F.col("__collect_geometry__")).alias(
+ "__collect_result_srid__"
+ ),
+ )
+ result = original_first(enriched)
+ result_srids.append(result["__collect_result_srid__"])
+ return result
+
+ # Spark 4 exposes the classic DataFrame as a concrete subclass of
+ # pyspark.sql.DataFrame, so patch the runtime class used by this frame.
+ monkeypatch.setattr(spark_frame_type, "first", count_first)
+
+ collect(series)
+
+ assert first_calls == 1
+ assert result_srids == [expected_srid]
+
+ def test_collect_distributed_geometry_families(self):
+ assert collect(GeoSeries([Point(0, 0), Point(1, 1)])).equals(
+ MultiPoint([(0, 0), (1, 1)])
+ )
+
+ lines = [
+ LineString([(0, 0), (1, 1)]),
+ LineString([(2, 2), (3, 3)]),
+ ]
+ collected_lines = collect(GeoSeries(lines))
+ assert collected_lines.geom_type == "MultiLineString"
+ assert len(collected_lines.geoms) == 2
+
+ if SHAPELY_GE_20:
+ empty_polygon = Polygon()
+ polygon = Polygon([(0, 0), (1, 0), (0, 1)])
+ for polygons in (
+ [empty_polygon, polygon],
+ [polygon, empty_polygon],
+ ):
+ collected_polygons = collect(GeoSeries(polygons))
+ assert collected_polygons.geom_type == "MultiPolygon"
+ assert len(collected_polygons.geoms) == 1
+
+ singleton_empty = collect(GeoSeries([empty_polygon]))
+ assert singleton_empty.geom_type == "Polygon"
+ assert singleton_empty.is_empty
+
+ for polygons in (
+ [empty_polygon],
+ [empty_polygon, empty_polygon],
+ ):
+ collected_empty = collect(
+ GeoSeries(polygons, crs="EPSG:4326"),
+ multi=True,
+ )
+ assert collected_empty.geom_type == "MultiPolygon"
+ assert collected_empty.is_empty
+ assert len(collected_empty.geoms) == 0
+ else:
+ polygons = [
+ Polygon([(0, 0), (1, 0), (0, 1)]),
+ Polygon([(2, 0), (3, 0), (2, 1)]),
+ ]
+ collected_polygons = collect(GeoSeries(polygons))
+ assert collected_polygons.geom_type == "MultiPolygon"
+ assert len(collected_polygons.geoms) == 2
+ with pytest.raises(ValueError, match="homogeneous"):
+ collect(GeoSeries([Polygon(), polygons[0]]))
+ with pytest.raises(KeyError, match="GeometryCollection"):
+ collect(GeoSeries([Polygon()]), multi=True)
+
+ with pytest.raises(ValueError, match="homogeneous"):
+ collect(
+ GeoSeries(
+ [
+ GeometryCollection(),
+ Polygon([(0, 0), (1, 0), (0, 1)]),
+ ]
+ )
+ )
+
+ def test_collect_validation_matches_geopandas(self):
+ with pytest.raises(IndexError, match="list index out of range"):
+ collect(GeoSeries([]))
+ with pytest.raises(AttributeError, match="geom_type"):
+ collect(GeoSeries([Point(0, 0), None]))
+ with pytest.raises(ValueError, match="homogeneous"):
+ collect(GeoSeries([Point(0, 0), LineString([(0, 0), (1, 1)])]))
+ with pytest.raises(ValueError, match="Cannot collect MultiPoint"):
+ collect(
+ GeoSeries(
+ [
+ MultiPoint([(0, 0)]),
+ MultiPoint([(1, 1)]),
+ ]
+ )
+ )
+ if SHAPELY_GE_20:
+ for empty, non_empty in (
+ (Point(), Point(0, 0)),
+ (LineString(), LineString([(0, 0), (1, 1)])),
+ ):
+ singleton_empty = collect(GeoSeries([empty]))
+ assert singleton_empty.geom_type == empty.geom_type
+ assert singleton_empty.is_empty
+ with pytest.raises(EmptyPartError, match="empty component"):
+ collect(GeoSeries([empty]), multi=True)
+ with pytest.raises(EmptyPartError, match="empty component"):
+ collect(GeoSeries([empty, non_empty]))
+ else:
+ with pytest.raises(KeyError, match="GeometryCollection"):
+ collect(GeoSeries([Point()]), multi=True)