Skip to content
Prev Previous commit
Next Next commit
new fix
  • Loading branch information
akkik04 committed Nov 24, 2025
commit 78f8ce7d476bb28650a21f74f6ee4d10be4edad9
26 changes: 0 additions & 26 deletions pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,14 +566,6 @@ def sanitize_array(
# extract ndarray or ExtensionArray, ensure we have no NumpyExtensionArray
data = extract_array(data, extract_numpy=True, extract_range=True)

# GH#61026: when 2D input is allowed (e.g. DataFrame column assignment),
# treat a (n, 1) numpy array as a 1D array of length n so downstream code
# (including pyarrow-backed StringArray) always sees 1D.
if allow_2d and isinstance(data, np.ndarray) and data.ndim == 2:
rows, cols = data.shape
if cols == 1:
data = data[:, 0]

if isinstance(data, np.ndarray) and data.ndim == 0:
if dtype is None:
dtype = data.dtype
Expand Down Expand Up @@ -619,24 +611,6 @@ def sanitize_array(
data = data.A

if dtype is None:
# GH#61026: special-case 2D+ object ndarrays when dtype is None.
if allow_2d and data.dtype == object and data.ndim > 1:
if data.ndim == 2 and data.shape[1] == 1:
# allow assigning a (n, 1) object array to a single column.
data = data[:, 0]
elif data.ndim == 2:
# more than 1 column, not allowed.
raise ValueError(
"Setting a DataFrame column with a 2D object array "
f"requires shape (n, 1); got shape {data.shape}."
)
else:
# ndim >= 3
raise ValueError(
f"Setting a DataFrame column with ndim {data.ndim} "
"object array is not supported."
)

subarr = data
if data.dtype == object and infer_object:
subarr = lib.maybe_convert_objects(
Expand Down
21 changes: 21 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -5501,7 +5501,28 @@ def _sanitize_column(self, value) -> tuple[ArrayLike, BlockValuesRefs | None]:
return _reindex_for_setitem(value, self.index)

if is_list_like(value):
# GH#61026: this method is only used for *single-column* assignment.
# Reject 2D/3D arrays here, except the (n, 1) case which we treat as 1D.
if isinstance(value, np.ndarray) and value.ndim > 1:
if value.ndim == 2:
if value.shape[1] == 1:
# (n, 1) → length-n 1D array
value = value[:, 0]
else:
# More than one column: users should use df[[...]] = value
raise ValueError(
"Setting a DataFrame column with a 2D array requires "
f"shape (n, 1); got shape {value.shape}."
)
else:
# ndim >= 3
raise ValueError(
f"Setting a DataFrame column with ndim {value.ndim} "
"array is not supported."
)

com.require_length_match(value, self.index)

return sanitize_array(value, self.index, copy=True, allow_2d=True), None

@property
Expand Down
Loading