Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: explode() fails if 'level_1' is in columns #1445

Merged
merged 4 commits into from May 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions geopandas/geodataframe.py
Expand Up @@ -877,6 +877,9 @@ def explode(self):
"""
df_copy = self.copy()

if "level_1" in df_copy.columns: # GH1393
df_copy = df_copy.rename(columns={"level_1": "__level_1"})

exploded_geom = df_copy.geometry.explode().reset_index(level=-1)
exploded_index = exploded_geom.columns[0]

Expand All @@ -887,6 +890,10 @@ def explode(self):
# exploded GeoSeries index.
df.set_index(exploded_index, append=True, inplace=True)
df.index.names = list(self.index.names) + [None]

if "__level_1" in df.columns:
df = df.rename(columns={"__level_1": "level_1"})

geo_df = df.set_geometry(self._geometry_column_name)
return geo_df

Expand Down
22 changes: 22 additions & 0 deletions geopandas/tests/test_geom_methods.py
Expand Up @@ -12,6 +12,7 @@
from geopandas.base import GeoPandasBase

from geopandas.tests.util import assert_geoseries_equal, geom_almost_equals, geom_equals
from geopandas._compat import PANDAS_GE_024
from pandas.testing import assert_frame_equal, assert_series_equal
import pytest

Expand Down Expand Up @@ -658,6 +659,27 @@ def test_explode_geodataframe(self, index_name):
expected_df = expected_df.set_index(expected_index)
assert_frame_equal(test_df, expected_df)

@pytest.mark.parametrize("index_name", [None, "test"])
def test_explode_geodataframe_level_1(self, index_name):
# GH1393
s = GeoSeries([MultiPoint([Point(1, 2), Point(2, 3)]), Point(5, 5)])
df = GeoDataFrame({"level_1": [1, 2], "geometry": s})
df.index.name = index_name

test_df = df.explode()

expected_s = GeoSeries([Point(1, 2), Point(2, 3), Point(5, 5)])
expected_df = GeoDataFrame({"level_1": [1, 1, 2], "geometry": expected_s})
expected_index = MultiIndex(
[[0, 1], [0, 1]], # levels
[[0, 0, 1], [0, 1, 0]], # labels/codes
names=[index_name, None],
)
expected_df = expected_df.set_index(expected_index)
if not PANDAS_GE_024:
expected_df = expected_df[["level_1", "geometry"]]
Comment on lines +679 to +680
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's some strange behaviour for old pandas, switching the order of columns, so I am switching it back.

assert_frame_equal(test_df, expected_df)

#
# Test '&', '|', '^', and '-'
#
Expand Down