Skip to content

Commit 53bd1a8

Browse files
tehuntermroeschke
andauthored
BUG: DataFrame slice selection treated as hashable in Python 3.12 #57500 (#58043)
* Reorder slice and hashable in __getitem__ * Add unit test * Fix test and formatting * Update whatsnew * Restore original flow ordering * Move whatsnew entry to 3.0.0 * Move whatsnew entry to Indexing * Update doc/source/whatsnew/v3.0.0.rst --------- Co-authored-by: Matthew Roeschke <[email protected]>
1 parent f8bd988 commit 53bd1a8

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ Interval
386386

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

392392
Missing

pandas/core/frame.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3855,8 +3855,10 @@ def __getitem__(self, key):
38553855
key = lib.item_from_zerodim(key)
38563856
key = com.apply_if_callable(key, self)
38573857

3858-
if is_hashable(key) and not is_iterator(key):
3858+
if is_hashable(key) and not is_iterator(key) and not isinstance(key, slice):
38593859
# is_iterator to exclude generator e.g. test_getitem_listlike
3860+
# As of Python 3.12, slice is hashable which breaks MultiIndex (GH#57500)
3861+
38603862
# shortcut if the key is in columns
38613863
is_mi = isinstance(self.columns, MultiIndex)
38623864
# GH#45316 Return view if key is not duplicated

pandas/tests/frame/indexing/test_indexing.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,16 @@ def test_loc_setitem_boolean_mask_allfalse(self):
524524
result.loc[result.b.isna(), "a"] = result.a.copy()
525525
tm.assert_frame_equal(result, df)
526526

527+
def test_getitem_slice_empty(self):
528+
df = DataFrame([[1]], columns=MultiIndex.from_product([["A"], ["a"]]))
529+
result = df[:]
530+
531+
expected = DataFrame([[1]], columns=MultiIndex.from_product([["A"], ["a"]]))
532+
533+
tm.assert_frame_equal(result, expected)
534+
# Ensure df[:] returns a view of df, not the same object
535+
assert result is not df
536+
527537
def test_getitem_fancy_slice_integers_step(self):
528538
df = DataFrame(np.random.default_rng(2).standard_normal((10, 5)))
529539

0 commit comments

Comments
 (0)