Skip to content

Commit fce6cc5

Browse files
author
Marco Gorelli
committed
Add fix and test for case of partially named multiindex
1 parent b4b21c7 commit fce6cc5

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

pandas/core/frame.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -6237,8 +6237,6 @@ def explode(self, column: Union[str, Tuple]) -> "DataFrame":
62376237
if not self.columns.is_unique:
62386238
raise ValueError("columns must be unique")
62396239

6240-
named_index = any(i for i in self.index.names)
6241-
62426240
column_with_index = self[column].reset_index()
62436241

62446242
result = (
@@ -6251,11 +6249,12 @@ def explode(self, column: Union[str, Tuple]) -> "DataFrame":
62516249
result.index = pandas.MultiIndex.from_frame(
62526250
result.iloc[:, : self.index.nlevels]
62536251
)
6252+
result.index.rename(
6253+
[i or None for num, i in enumerate(self.index.names)], inplace=True
6254+
)
62546255
else:
62556256
result.index = result.iloc[:, 0]
6256-
6257-
if not named_index:
6258-
result.index.names = [None] * self.index.nlevels
6257+
result.index.rename(self.index.name or None, inplace=True)
62596258

62606259
result = result.reindex(columns=self.columns, copy=False)
62616260

pandas/tests/frame/test_explode.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,18 @@ def test_usecase():
176176
),
177177
pd.DataFrame(
178178
{"col": [1, 2, 3, 4], "other_col": ["a", "a", "b", "b"]},
179-
index=pd.MultiIndex.from_tuples([(0, 1), (0, 1), (0, 1), (0, 1)]),
179+
pd.MultiIndex.from_tuples([(0, 1), (0, 1), (0, 1), (0, 1)]),
180+
dtype=object,
181+
),
182+
),
183+
(
184+
pd.DataFrame(
185+
{"col": [[1, 2], [3, 4]], "other_col": ["a", "b"]},
186+
pd.MultiIndex.from_arrays([[0, 0], [1, 1]], names=['foo', None]),
187+
),
188+
pd.DataFrame(
189+
{"col": [1, 2, 3, 4], "other_col": ["a", "a", "b", "b"]},
190+
pd.MultiIndex.from_arrays([[0, 0, 0, 0], [1, 1, 1, 1]], names=['foo', None]),
180191
dtype=object,
181192
),
182193
),

0 commit comments

Comments
 (0)