BUG: Unexpected behavior of setting item to DataFrame slice · Issue #40440 · pandas-dev/pandas (original) (raw)


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4], 'col3': [6, 7]}) df[1:] = [1, 2, 3]

Problem description

I get the ValueError: cannot set using a slice indexer with a different length than the value, when running the above code snippet. However, when running the following one, the error doesn't appear:

df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4], 'col3': [6, 7]}) df[1:] = ['a', 'b', 'c'] df[1:] = [1, 2, 3]

Looks like assigning value to slice have different behavior depending on type on the value, which doesn't seem to be intended and is not documented.

Another example is:

df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4], 'e': [6, 7]}) df[1:] = ['a', 'b', 'c'] df[pd.DataFrame({'col1': [True, True], 'col2': [False, True]})] = [2, 3, 4]

raises ValueError: cannot assign mismatch length to masked array for line 3, but this code doesn't:

df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4], 'e': [6, 7]}) df[pd.DataFrame({'col1': [True, True], 'col2': [False, True]})] = [2, 3, 4]

Expected Output

Exceptions thrown should be the same regardless of the previous calls on the given data frame. If assigning value of array of strings have some special meaning, it should be documented. String array assignment shouldn't change behavior of succeeding calls.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : f2c8480
python : 3.8.6.final.0
python-bits : 64
OS : Darwin
OS-release : 20.3.0
Version : Darwin Kernel Version 20.3.0: Thu Jan 21 00:07:06 PST 2021; root:xnu-7195.81.3~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : pl_PL.UTF-8
pandas : 1.2.3
numpy : 1.20.1
pytz : 2021.1
dateutil : 2.8.1
pip : 20.2.3
setuptools : 50.3.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None