From cebb5873d04a81bf37376dfb5d4b2adcfe9d87af Mon Sep 17 00:00:00 2001 From: Matt Richards <45483497+m-richards@users.noreply.github.com> Date: Thu, 20 Jan 2022 19:18:46 +1000 Subject: [PATCH] REGR: fix bug in apply when returning a series (#2286) --- geopandas/geodataframe.py | 5 ++++- geopandas/tests/test_pandas_methods.py | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/geopandas/geodataframe.py b/geopandas/geodataframe.py index 25c2793..f39f875 100644 --- a/geopandas/geodataframe.py +++ b/geopandas/geodataframe.py @@ -1408,7 +1408,10 @@ individually so that features may have different properties func, axis=axis, raw=raw, result_type=result_type, args=args, **kwargs ) # Reconstruct gdf if it was lost by apply - if self._geometry_column_name in result.columns: + if ( + isinstance(result, DataFrame) + and self._geometry_column_name in result.columns + ): # axis=1 apply will split GeometryDType to object, try and cast back try: result = result.set_geometry(self._geometry_column_name) diff --git a/geopandas/tests/test_pandas_methods.py b/geopandas/tests/test_pandas_methods.py index c6d0420..72dbcff 100644 --- a/geopandas/tests/test_pandas_methods.py +++ b/geopandas/tests/test_pandas_methods.py @@ -652,6 +652,15 @@ def test_apply_preserves_geom_col_name(df): assert result.geometry.name == "geom" +def test_df_apply_returning_series(df): + # https://github.com/geopandas/geopandas/issues/2283 + result = df.apply(lambda row: row.geometry, axis=1) + assert_geoseries_equal(result, df.geometry, check_crs=False) + + result = df.apply(lambda row: row.value1, axis=1) + assert_series_equal(result, df["value1"].rename(None)) + + @pytest.mark.skipif(not compat.PANDAS_GE_10, reason="attrs introduced in pandas 1.0") def test_preserve_attrs(df): # https://github.com/geopandas/geopandas/issues/1654