Skip to content

Commit

Permalink
BUG: setting dataframe column to 2d array with more than one col
Browse files Browse the repository at this point in the history
References this issue on Github:
pandas-dev#40827
  • Loading branch information
Mxchaeltrxn committed Apr 17, 2021
1 parent b966657 commit ffe6cca
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pandas/core/frame.py
Expand Up @@ -3843,6 +3843,14 @@ def reindexer(value):
else:
value = com.asarray_tuplesafe(value)
elif value.ndim == 2:
value_cols = value.shape[1]
if value_cols > 1:
raise ValueError(
f"Dataframe column '{key}' is being "
"assigned to a 2D array with more than "
"two columns. Column assignment accepts "
"only 2D arrays with one column."
)
value = value.copy().T
elif isinstance(value, Index):
value = value.copy(deep=True)
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/frame/indexing/test_setitem.py
@@ -1,3 +1,5 @@
from hypothesis import given, settings, strategies as st
from hypothesis.extra.numpy import arrays
import numpy as np
import pytest

Expand All @@ -22,6 +24,29 @@


class TestDataFrameSetItem:
@settings(max_examples=200)
@given(
st.one_of(
[
arrays(dtype=str, shape=(4, 2)),
arrays(dtype=float, shape=(4, 2)),
arrays(dtype=int, shape=(4, 2)),
arrays(dtype=str, shape=(4, 5)),
arrays(dtype=float, shape=(4, 5)),
arrays(dtype=int, shape=(4, 5)),
]
)
)
def test__setitem_size_incompatible_ndarray(self, arr):
data = DataFrame(np.zeros((4, 2)), columns=["A", "B"])
msg = (
"Dataframe column 'A' is being assigned to a 2D "
"array with more than two columns. Column assignment "
"accepts only 2D arrays with one column."
)
with pytest.raises(Exception, match=msg):
data["A"] = arr

@pytest.mark.parametrize("dtype", ["int32", "int64", "float32", "float64"])
def test_setitem_dtype(self, dtype, float_frame):
arr = np.random.randn(len(float_frame))
Expand Down

0 comments on commit ffe6cca

Please sign in to comment.