Skip to content

Commit c647e57

Browse files
author
Marco Gorelli
committed
Add fix and test for case of partially named multiindex
1 parent 3d12d61 commit c647e57

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
@@ -6244,8 +6244,6 @@ def explode(self, column: Union[str, Tuple]) -> "DataFrame":
62446244
if not self.columns.is_unique:
62456245
raise ValueError("columns must be unique")
62466246

6247-
named_index = any(i for i in self.index.names)
6248-
62496247
column_with_index = self[column].reset_index()
62506248

62516249
result = (
@@ -6258,11 +6256,12 @@ def explode(self, column: Union[str, Tuple]) -> "DataFrame":
62586256
result.index = pandas.MultiIndex.from_frame(
62596257
result.iloc[:, : self.index.nlevels]
62606258
)
6259+
result.index.rename(
6260+
[i or None for num, i in enumerate(self.index.names)], inplace=True
6261+
)
62616262
else:
62626263
result.index = result.iloc[:, 0]
6263-
6264-
if not named_index:
6265-
result.index.names = [None] * self.index.nlevels
6264+
result.index.rename(self.index.name or None, inplace=True)
62666265

62676266
result = result.reindex(columns=self.columns, copy=False)
62686267

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)