Skip to content

Commit 179ef1b

Browse files
committed
BUG: reset_index doesn't preserve dtype on empty frame with MultiIndex
1 parent 506eb54 commit 179ef1b

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
@@ -934,6 +934,7 @@ Indexing
934934
- Bug in :meth:`Series.at` when used with a :class:`MultiIndex` would raise an exception on valid inputs (:issue:`26989`)
935935
- Bug in :meth:`DataFrame.loc` with dictionary of values changes columns with dtype of ``int`` to ``float`` (:issue:`34573`)
936936
- Bug in :meth:`Series.loc` when used with a :class:`MultiIndex` would raise an IndexingError when accessing a None value (:issue:`34318`)
937+
- 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`)
937938

938939
Missing
939940
^^^^^^^

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4679,7 +4679,7 @@ def _maybe_casted_values(index, labels=None):
46794679
# we can have situations where the whole mask is -1,
46804680
# meaning there is nothing found in labels, so make all nan's
46814681
if mask.all():
4682-
values = np.empty(len(mask))
4682+
values = np.empty(len(mask), dtype=index.dtype)
46834683
values.fill(np.nan)
46844684
else:
46854685
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)