Skip to content

Commit a5277ff

Browse files
author
Marco Gorelli
committed
Add fix and test for case of partially named multiindex
1 parent 19b3d57 commit a5277ff

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

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

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

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

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)