diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index dda20fe8aeb21..ab619feebee9f 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -1217,6 +1217,7 @@ Indexing - Bug in :meth:`DataFrame.__setitem__` on an empty :class:`DataFrame` with a tuple corrupting the frame (:issue:`54385`) - Bug in :meth:`DataFrame.from_records` throwing a ``ValueError`` when passed an empty list in ``index`` (:issue:`58594`) - Bug in :meth:`DataFrame.loc` and :meth:`DataFrame.iloc` returning incorrect dtype when selecting from a :class:`DataFrame` with mixed data types. (:issue:`60600`) +- Bug in :meth:`DataFrame.loc` returning incorrect dtype when the key is ``slice`` (:issue:`63071`) - Bug in :meth:`DataFrame.loc` with inconsistent behavior of loc-set with 2 given indexes to Series (:issue:`59933`) - Bug in :meth:`Index.equals` when comparing between :class:`Series` with string dtype :class:`Index` (:issue:`61099`) - Bug in :meth:`Index.get_indexer` and similar methods when ``NaN`` is located at or after position 128 (:issue:`58924`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index a476415d6c7c0..6c4f34ac5afc3 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1087,7 +1087,11 @@ def _getitem_lowerdim(self, tup: tuple): # Reverse tuple so that we are indexing along columns before rows # and avoid unintended dtype inference. # GH60600 for i, key in zip(range(len(tup) - 1, -1, -1), reversed(tup), strict=True): - if is_label_like(key) or is_list_like(key): + if ( + is_label_like(key) + or is_list_like(key) + or (isinstance(key, slice) and need_slice(key)) + ): # We don't need to check for tuples here because those are # caught by the _is_nested_tuple_indexer check above. section = self._getitem_axis(key, axis=i) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 91111d0b1b0ea..026456f69d43f 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -61,10 +61,11 @@ def test_not_change_nan_loc(series, new_series, expected_ser): tm.assert_frame_equal(df.notna(), ~expected) -def test_loc_dtype(): +@pytest.mark.parametrize("key", [[1, 2], slice(1, 3)]) +def test_loc_dtype(key): # GH 60600 df = DataFrame([["a", 1.0, 2.0], ["b", 3.0, 4.0]]) - result = df.loc[0, [1, 2]] + result = df.loc[0, key] expected = Series([1.0, 2.0], index=[1, 2], dtype=float, name=0) tm.assert_series_equal(result, expected)