Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: loc assignment with a numpy array fails when MultiIndex columns are not sorted #38601

Closed
1 task
mosalx opened this issue Dec 21, 2020 · 5 comments · Fixed by #39071
Closed
1 task

BUG: loc assignment with a numpy array fails when MultiIndex columns are not sorted #38601

mosalx opened this issue Dec 21, 2020 · 5 comments · Fixed by #39071
Labels
Bug Indexing Related to indexing on series/frames, not to indexes themselves MultiIndex Regression Functionality that used to work in a prior pandas version
Milestone

Comments

@mosalx
Copy link

mosalx commented Dec 21, 2020

  • [ x] I have checked that this issue has not already been reported.

  • [x ] I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


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)
<ipython-input-5-4dac1c2ec043> in <module>
----> 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
@mosalx mosalx added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Dec 21, 2020
simonjayhawkins added a commit to simonjayhawkins/pandas that referenced this issue Dec 22, 2020
@simonjayhawkins
Copy link
Member

Thanks @mosalx for the report

This issue affects pandas 1.1.5 and 1.1.0 but not 1.0.5.

first bad commit: [33f67d9] BUG: iloc.setitem with duplicate columns (#32477) cc @jbrockmendel

@simonjayhawkins simonjayhawkins added Indexing Related to indexing on series/frames, not to indexes themselves MultiIndex Regression Functionality that used to work in a prior pandas version and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Dec 22, 2020
@simonjayhawkins simonjayhawkins added this to the Contributions Welcome milestone Dec 22, 2020
@marianayap
Copy link

take

@reidswanson
Copy link

This seems to have reemerged as a problem. I get the same exception in Pandas 1.4.0, but rolling back to 1.2.1 fixes the issue.

@simonjayhawkins
Copy link
Member

can't reproduce. Code sample works in 1.4.0 for me. can you open a new issue with a reproducible minimum example and output of show versions. A closed issue is less likely to get so much attention.

@reidswanson
Copy link

reidswanson commented Feb 11, 2022

You're right. I was doing something like:

col_list_a = ['a1', 'a2', 'a2', 'a3']
col_list_b = ['b1', 'b2', 'b2', 'b3']
x.loc[x['bool_col'], col_list_a] = (
    x.loc[x['bool_col'], col_list_a].to_numpy()
    - x.loc[x['bool_col'], col_list_b].to_numpy()
)

Pandas 1.2.1 appears to ignore the fact that column a2 and b2 have been listed twice, but in Pandas > 1.2.1 it raises an exception.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Indexing Related to indexing on series/frames, not to indexes themselves MultiIndex Regression Functionality that used to work in a prior pandas version
Projects
None yet
5 participants