Skip to content

BUG: DataFrame slice selection treated as hashable in Python 3.12 #57500 #58043

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Apr 16, 2024
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ Interval

Indexing
^^^^^^^^
-
- Bug in :meth:`DataFrame.__getitem__` returning modified columns when called with ``slice`` in Python 3.12 (:issue:`57500`)
-

Missing
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3855,8 +3855,10 @@ def __getitem__(self, key):
key = lib.item_from_zerodim(key)
key = com.apply_if_callable(key, self)

if is_hashable(key) and not is_iterator(key):
if is_hashable(key) and not is_iterator(key) and not isinstance(key, slice):
# is_iterator to exclude generator e.g. test_getitem_listlike
# As of Python 3.12, slice is hashable which breaks MultiIndex (GH#57500)

# shortcut if the key is in columns
is_mi = isinstance(self.columns, MultiIndex)
# GH#45316 Return view if key is not duplicated
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/frame/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,16 @@ def test_loc_setitem_boolean_mask_allfalse(self):
result.loc[result.b.isna(), "a"] = result.a.copy()
tm.assert_frame_equal(result, df)

def test_getitem_slice_empty(self):
df = DataFrame([[1]], columns=MultiIndex.from_product([["A"], ["a"]]))
result = df[:]

expected = DataFrame([[1]], columns=MultiIndex.from_product([["A"], ["a"]]))

tm.assert_frame_equal(result, expected)
# Ensure df[:] returns a view of df, not the same object
assert result is not df

def test_getitem_fancy_slice_integers_step(self):
df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))

Expand Down
Loading