@@ -5501,29 +5501,31 @@ def _sanitize_column(self, value) -> tuple[ArrayLike, BlockValuesRefs | None]:
55015501 return _reindex_for_setitem (value , self .index )
55025502
55035503 if is_list_like (value ):
5504- # GH#61026: this method is only used for *single-column* assignment.
5505- # Reject 2D/3D arrays here, except the (n, 1) case which we treat as 1D.
5506- if isinstance (value , np .ndarray ) and value .ndim > 1 :
5507- if value .ndim == 2 :
5508- if value .shape [1 ] == 1 :
5509- # (n, 1) → length-n 1D array
5510- value = value [:, 0 ]
5511- else :
5512- # More than one column: users should use df[[...]] = value
5513- raise ValueError (
5514- "Setting a DataFrame column with a 2D array requires "
5515- f"shape (n, 1); got shape { value .shape } ."
5516- )
5517- else :
5518- # ndim >= 3
5519- raise ValueError (
5520- f"Setting a DataFrame column with ndim { value .ndim } "
5521- "array is not supported."
5522- )
5523-
55245504 com .require_length_match (value , self .index )
55255505
5526- return sanitize_array (value , self .index , copy = True , allow_2d = True ), None
5506+ # GH#61026: special-case 2D inputs for single-column assignment.
5507+ # - accept shape (n, 1) by flattening to 1D
5508+ # - disallow 2D *object* arrays with more than one column, since those
5509+ # correspond to a single column key and should be rejected
5510+ arr = value
5511+
5512+ # np.matrix is always 2D; gonna convert to regular ndarray
5513+ if isinstance (arr , np .matrix ):
5514+ arr = np .asarray (arr )
5515+
5516+ if isinstance (arr , np .ndarray ) and arr .ndim == 2 :
5517+ if arr .shape [1 ] == 1 :
5518+ # treating (n, 1) as a length-n 1D array
5519+ arr = arr [:, 0 ]
5520+ elif arr .dtype == object :
5521+ # single-column setitem with a 2D object array is not allowed.
5522+ msg = (
5523+ "Setting a DataFrame column with a 2D array requires "
5524+ f"shape (n, 1); got shape { arr .shape } ."
5525+ )
5526+ raise ValueError (msg )
5527+ subarr = sanitize_array (arr , self .index , copy = True , allow_2d = True )
5528+ return subarr , None
55275529
55285530 @property
55295531 def _series (self ):
0 commit comments