Skip to content

Commit 9b4fd9b

Browse files
authored
BUG: reset_index doesn't preserve dtype on empty frame with MultiIndex (#34942)
1 parent 3e8f14f commit 9b4fd9b

File tree

4 files changed

+20
-1
lines changed

4 files changed

+20
-1
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -953,6 +953,7 @@ Indexing
953953
- Bug in :meth:`Series.at` when used with a :class:`MultiIndex` would raise an exception on valid inputs (:issue:`26989`)
954954
- Bug in :meth:`DataFrame.loc` with dictionary of values changes columns with dtype of ``int`` to ``float`` (:issue:`34573`)
955955
- Bug in :meth:`Series.loc` when used with a :class:`MultiIndex` would raise an IndexingError when accessing a None value (:issue:`34318`)
956+
- Bug in :meth:`DataFrame.reset_index` and :meth:`Series.reset_index` would not preserve data types on an empty :class:`DataFrame` or :class:`Series` with a :class:`MultiIndex` (:issue:`19602`)
956957

957958
Missing
958959
^^^^^^^

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4723,7 +4723,7 @@ def _maybe_casted_values(index, labels=None):
47234723
# we can have situations where the whole mask is -1,
47244724
# meaning there is nothing found in labels, so make all nan's
47254725
if mask.all():
4726-
values = np.empty(len(mask))
4726+
values = np.empty(len(mask), dtype=index.dtype)
47274727
values.fill(np.nan)
47284728
else:
47294729
values = values.take(labels)

pandas/tests/frame/methods/test_reset_index.py

+8
Original file line numberDiff line numberDiff line change
@@ -297,3 +297,11 @@ def test_reset_index_range(self):
297297
index=RangeIndex(stop=2),
298298
)
299299
tm.assert_frame_equal(result, expected)
300+
301+
302+
def test_reset_index_dtypes_on_empty_frame_with_multiindex():
303+
# GH 19602 - Preserve dtype on empty DataFrame with MultiIndex
304+
idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], ["a", "b"]])
305+
result = DataFrame(index=idx)[:0].reset_index().dtypes
306+
expected = Series({"level_0": np.int64, "level_1": np.float64, "level_2": object})
307+
tm.assert_series_equal(result, expected)

pandas/tests/series/methods/test_reset_index.py

+10
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,13 @@ def test_reset_index_drop_errors(self):
108108
s = Series(range(4), index=MultiIndex.from_product([[1, 2]] * 2))
109109
with pytest.raises(KeyError, match="not found"):
110110
s.reset_index("wrong", drop=True)
111+
112+
113+
def test_reset_index_dtypes_on_empty_series_with_multiindex():
114+
# GH 19602 - Preserve dtype on empty Series with MultiIndex
115+
idx = MultiIndex.from_product([[0, 1], [0.5, 1.0], ["a", "b"]])
116+
result = Series(dtype=object, index=idx)[:0].reset_index().dtypes
117+
expected = Series(
118+
{"level_0": np.int64, "level_1": np.float64, "level_2": object, 0: object}
119+
)
120+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)