Repository: pandas-dev/pandas

Issue:
Explode on identical index causes duplication
#### Code Sample, a copy-pastable example if possible

```python
>>> df = pd.DataFrame({'col': [['a', 'b'], ['c', 'd']]}, index=[0,0])
>>> df.explode('col')
  col
0   a
0   b
0   c
0   d
0   a
0   b
0   c
0   d
```
#### Problem description
I'm not sure if this is expected behaviour. But it took me slightly off guard when I had a datetime index with occasionally identical timestamps. This is the output I expected:
```python
  col
0   a
0   b
0   c
0   d
```
Thanks for your work on pandas! Apologies if this is actually normal behaviour.

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit           : None
python           : 3.6.7.final.0
python-bits      : 64
OS               : Linux
OS-release       : 4.4.0-139-generic
machine          : x86_64
processor        : x86_64
byteorder        : little
LC_ALL           : en_US.UTF-8
LANG             : en_US
LOCALE           : en_US.UTF-8

pandas           : 0.25.0
numpy            : 1.14.3
pytz             : 2018.9
dateutil         : 2.8.0
pip              : 19.0.2
setuptools       : 40.8.0
Cython           : None
pytest           : 4.5.0
hypothesis       : None
sphinx           : None
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 2.10
IPython          : 7.3.0
pandas_datareader: None
bs4              : None
bottleneck       : None
fastparquet      : None
gcsfs            : None
lxml.etree       : None
matplotlib       : 3.0.2
numexpr          : None
odfpy            : None
openpyxl         : None
pandas_gbq       : None
pyarrow          : None
pytables         : None
s3fs             : None
scipy            : 1.2.1
sqlalchemy       : None
tables           : None
xarray           : None
xlrd             : None
xlwt             : None
xlsxwriter       : None

</details>



Discussion:
Hmm thanks for the report. Duplicating like this probably isn't deliberate...
Seems to only happen to frames (not series):

```
>>> pd.Series([[1,2], [3,4]], index=[0, 0]).to_frame('col').explode('col')
  col
0   1
0   2
0   3
0   4
0   1
0   2
0   3
0   4
>>> pd.Series([[1,2], [3,4]], index=[0, 0]).explode()
0    1
0    2
0    3
0    4
dtype: object
```

Resolving patch:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6267,12 +6267,13 @@ def explode(self, column: Union[str, Tuple]) -> "DataFrame":
         if not self.columns.is_unique:
             raise ValueError("columns must be unique")
 
-        result = self[column].explode()
-        return (
-            self.drop([column], axis=1)
-            .join(result)
-            .reindex(columns=self.columns, copy=False)
-        )
+        df = self.reset_index(drop=True)
+        result = df[column].explode()
+        result = df.drop([column], axis=1).join(result)
+        result.index = self.index.take(result.index)
+        result = result.reindex(columns=self.columns, copy=False)
+
+        return result
 
     def unstack(self, level=-1, fill_value=None):
         """


Test patch:
diff --git a/pandas/tests/frame/test_explode.py b/pandas/tests/frame/test_explode.py
--- a/pandas/tests/frame/test_explode.py
+++ b/pandas/tests/frame/test_explode.py
@@ -118,3 +118,47 @@ def test_usecase():
         index=[0, 0, 1, 1],
     )
     tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+    "input_dict, input_index, expected_dict, expected_index",
+    [
+        (
+            {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},
+            [0, 0],
+            {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},
+            [0, 0, 0, 0],
+        ),
+        (
+            {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},
+            pd.Index([0, 0], name="my_index"),
+            {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},
+            pd.Index([0, 0, 0, 0], name="my_index"),
+        ),
+        (
+            {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},
+            pd.MultiIndex.from_arrays(
+                [[0, 0], [1, 1]], names=["my_first_index", "my_second_index"]
+            ),
+            {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},
+            pd.MultiIndex.from_arrays(
+                [[0, 0, 0, 0], [1, 1, 1, 1]],
+                names=["my_first_index", "my_second_index"],
+            ),
+        ),
+        (
+            {"col1": [[1, 2], [3, 4]], "col2": ["foo", "bar"]},
+            pd.MultiIndex.from_arrays([[0, 0], [1, 1]], names=["my_index", None]),
+            {"col1": [1, 2, 3, 4], "col2": ["foo", "foo", "bar", "bar"]},
+            pd.MultiIndex.from_arrays(
+                [[0, 0, 0, 0], [1, 1, 1, 1]], names=["my_index", None]
+            ),
+        ),
+    ],
+)
+def test_duplicate_index(input_dict, input_index, expected_dict, expected_index):
+    # GH 28005
+    df = pd.DataFrame(input_dict, index=input_index)
+    result = df.explode("col1")
+    expected = pd.DataFrame(expected_dict, index=expected_index, dtype=object)
+    tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/series/test_explode.py b/pandas/tests/series/test_explode.py
--- a/pandas/tests/series/test_explode.py
+++ b/pandas/tests/series/test_explode.py
@@ -111,3 +111,11 @@ def test_nested_EA():
         pd.date_range("20170101", periods=6, tz="UTC"), index=[0, 0, 0, 1, 1, 1]
     )
     tm.assert_series_equal(result, expected)
+
+
+def test_duplicate_index():
+    # GH 28005
+    s = pd.Series([[1, 2], [3, 4]], index=[0, 0])
+    result = s.explode()
+    expected = pd.Series([1, 2, 3, 4], index=[0, 0, 0, 0], dtype=object)
+    tm.assert_series_equal(result, expected)