From 882d091215ef355eb5fe172b9e4eca5e56e6bd94 Mon Sep 17 00:00:00 2001 From: Daniel Saxton Date: Thu, 18 Mar 2021 17:59:26 -0500 Subject: [PATCH] BUG: Respect ignore_index in Series.explode --- doc/source/whatsnew/v1.3.0.rst | 1 + pandas/core/series.py | 3 ++- pandas/tests/series/methods/test_explode.py | 8 ++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 9c8968f7f8223..77fdf38416f8c 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -630,6 +630,7 @@ Reshaping - Allow :class:`Index` to be passed to the :func:`numpy.all` function (:issue:`40180`) - Bug in :meth:`DataFrame.stack` not preserving ``CategoricalDtype`` in a ``MultiIndex`` (:issue:`36991`) - Bug in :func:`to_datetime` raising error when input sequence contains unhashable items (:issue:`39756`) +- Bug in :meth:`Series.explode` preserving index when ``ignore_index`` was ``True`` and values were scalars (:issue:`40487`) Sparse ^^^^^^ diff --git a/pandas/core/series.py b/pandas/core/series.py index 83eb4c38bc163..27042f7de9dc1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3857,7 +3857,8 @@ def explode(self, ignore_index: bool = False) -> Series: dtype: object """ if not len(self) or not is_object_dtype(self): - return self.copy() + result = self.copy() + return result.reset_index(drop=True) if ignore_index else result values, counts = reshape.explode(np.asarray(self._values)) diff --git a/pandas/tests/series/methods/test_explode.py b/pandas/tests/series/methods/test_explode.py index 1f0fbd1cc5ecb..c73737dad89aa 100644 --- a/pandas/tests/series/methods/test_explode.py +++ b/pandas/tests/series/methods/test_explode.py @@ -134,3 +134,11 @@ def test_explode_sets(): result = s.explode().sort_values() expected = pd.Series(["a", "b", "c"], index=[1, 1, 1]) tm.assert_series_equal(result, expected) + + +def test_explode_scalars_can_ignore_index(): + # https://github.com/pandas-dev/pandas/issues/40487 + s = pd.Series([1, 2, 3], index=["a", "b", "c"]) + result = s.explode(ignore_index=True) + expected = pd.Series([1, 2, 3]) + tm.assert_series_equal(result, expected)