BUG: loc assignment with a numpy array fails when MultiIndex columns are not sorted · Issue #38601 · 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

import numpy as np import pandas as pd

create a dataframe with non-lexsorted multilevel columns

df = pd.DataFrame(np.arange(12).reshape(3,4), columns=pd.MultiIndex.from_tuples([('B', 1), ('B', 2), ('A', '3'), ('A', '4')]))

df_sorted_columns = df.sort_index(1) # a copy with sorted columns df_sorted_columns.loc[:, 'A'] = np.zeros((3, 2)) # works fine

df.loc[:, 'A'] = np.zeros((3, 2)) # ValueError: Must have equal len keys and value when setting with an ndarray

df.loc[:, ['A']] = np.zeros((3, 2)) # works fine df.loc[:, ('A', slice(None))] = np.zeros((3, 2)) # works fine

Problem description

Assigning a numpy array to a subset of columns using 'loc' behaves inconsistently with multi-level columns. The behavior depends on the lexsort state of the column index. If the columns are not lexsorted, the assignment fails as shown in the code example. Otherwise the assignment succeeds. This issue affects pandas 1.1.5 and 1.1.0 but not 1.0.5.

Expected Output

'loc' assignment is expected to succeed regardless of the columns' lexsort state

Output of pd.show_versions()

INSTALLED VERSIONS

commit : b5958ee
python : 3.8.5.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.18362
machine : AMD64
processor : Intel64 Family 6 Model 158 Stepping 10, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252

pandas : 1.1.5
numpy : 1.19.2
pytz : 2020.4
dateutil : 2.8.1
pip : 20.3.3
setuptools : 51.0.0.post20201207
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.19.0
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
pytables : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Traceback


ValueError Traceback (most recent call last) in ----> 1 df.loc[:, 'A'] = np.zeros((3, 2)) 2 df

~\AppData\Local\Continuum\miniconda3\envs\pandas110\lib\site-packages\pandas\core\indexing.py in setitem(self, key, value) 668 669 iloc = self if self.name == "iloc" else self.obj.iloc --> 670 iloc._setitem_with_indexer(indexer, value) 671 672 def _validate_key(self, key, axis: int):

~\AppData\Local\Continuum\miniconda3\envs\pandas110\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value) 1727 value = np.array(value, dtype=object) 1728 if len(ilocs) != value.shape[1]: -> 1729 raise ValueError( 1730 "Must have equal len keys and value " 1731 "when setting with an ndarray"

ValueError: Must have equal len keys and value when setting with an ndarray