Skip to content

Commit 65a2a74

Browse files
authored
BUG: empty_frame[tuple] = values corrupting frame (#63002)
1 parent 930b66d commit 65a2a74

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1132,6 +1132,7 @@ Indexing
11321132
^^^^^^^^
11331133
- Bug in :meth:`DataFrame.__getitem__` returning modified columns when called with ``slice`` in Python 3.12 (:issue:`57500`)
11341134
- Bug in :meth:`DataFrame.__getitem__` when slicing a :class:`DataFrame` with many rows raised an ``OverflowError`` (:issue:`59531`)
1135+
- Bug in :meth:`DataFrame.__setitem__` on an empty :class:`DataFrame` with a tuple corrupting the frame (:issue:`54385`)
11351136
- Bug in :meth:`DataFrame.from_records` throwing a ``ValueError`` when passed an empty list in ``index`` (:issue:`58594`)
11361137
- Bug in :meth:`DataFrame.loc` and :meth:`DataFrame.iloc` returning incorrect dtype when selecting from a :class:`DataFrame` with mixed data types. (:issue:`60600`)
11371138
- Bug in :meth:`DataFrame.loc` with inconsistent behavior of loc-set with 2 given indexes to Series (:issue:`59933`)

pandas/core/indexes/base.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5193,7 +5193,9 @@ def _validate_fill_value(self, value):
51935193
"""
51945194
dtype = self.dtype
51955195
if isinstance(dtype, np.dtype) and dtype.kind not in "mM":
5196-
# return np_can_hold_element(dtype, value)
5196+
if isinstance(value, tuple) and dtype != object:
5197+
# GH#54385
5198+
raise TypeError
51975199
try:
51985200
return np_can_hold_element(dtype, value)
51995201
except LossySetitemError as err:
@@ -6357,6 +6359,10 @@ def _find_common_type_compat(self, target) -> DtypeObj:
63576359
"""
63586360
target_dtype, _ = infer_dtype_from(target)
63596361

6362+
if isinstance(target, tuple):
6363+
# GH#54385
6364+
return np.dtype(object)
6365+
63606366
if using_string_dtype():
63616367
# special case: if left or right is a zero-length RangeIndex or
63626368
# Index[object], those can be created by the default empty constructors

pandas/tests/frame/indexing/test_setitem.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1002,6 +1002,15 @@ def test_loc_expansion_with_timedelta_type(self):
10021002
)
10031003
tm.assert_frame_equal(result, expected)
10041004

1005+
def test_setitem_tuple_key_in_empty_frame(self):
1006+
# GH#54385
1007+
df = DataFrame()
1008+
df[(0, 0)] = [1, 2, 3]
1009+
1010+
cols = Index([(0, 0)], tupleize_cols=False)
1011+
expected = DataFrame({(0, 0): [1, 2, 3]}, columns=cols)
1012+
tm.assert_frame_equal(df, expected)
1013+
10051014

10061015
class TestDataFrameSetItemSlicing:
10071016
def test_setitem_slice_position(self):

0 commit comments

Comments
 (0)