diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 4a6cf117fd196..f7b49b81d767c 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -694,6 +694,7 @@ Interval Indexing ^^^^^^^^ - Bug in :meth:`DataFrame.__getitem__` returning modified columns when called with ``slice`` in Python 3.12 (:issue:`57500`) +- Bug in :meth:`DataFrame.__setitem__` throwing a ``ValueError`` when setting a column with a 2D object array (:issue:`61026`) - Bug in :meth:`DataFrame.from_records` throwing a ``ValueError`` when passed an empty list in ``index`` (:issue:`58594`) - Bug in :meth:`DataFrame.loc` with inconsistent behavior of loc-set with 2 given indexes to Series (:issue:`59933`) - Bug in :meth:`MultiIndex.insert` when a new value inserted to a datetime-like level gets cast to ``NaT`` and fails indexing (:issue:`60388`) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index ada492787a179..23b292c34eca4 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -612,7 +612,12 @@ def sanitize_array( if dtype is None: subarr = data if data.dtype == object and infer_object: - subarr = maybe_infer_to_datetimelike(data) + if data.ndim != 1: + # GH#61026 + subarr = data.ravel() + if copy: + subarr = subarr.copy() + subarr = maybe_infer_to_datetimelike(subarr) elif data.dtype.kind == "U" and using_string_dtype(): from pandas.core.arrays.string_ import StringDtype diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 20dd7b0c4d3e7..e7e119b8bf32c 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -816,6 +816,23 @@ def test_setitem_index_object_dtype_not_inferring(self): ) tm.assert_frame_equal(df, expected) + def test_setitem_2d_object_array(self): + # GH#61026 + df = DataFrame( + { + "c1": [1, 2, 3, 4, 5], + } + ) + arr = np.array([["A"], ["B"], ["C"], ["D"], ["E"]], dtype=object) + df["c1"] = arr + + expected = DataFrame( + { + "c1": ["A", "B", "C", "D", "E"], + } + ) + tm.assert_frame_equal(df, expected) + class TestSetitemTZAwareValues: @pytest.fixture