Skip to content

BUG: DataFrame.drop fails when there is a multiIndex without any level provided #36293

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

Closed
2 of 3 tasks
galipremsagar opened this issue Sep 11, 2020 · 5 comments · Fixed by #38220
Closed
2 of 3 tasks
Labels
MultiIndex Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Milestone

Comments

@galipremsagar
Copy link

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

  • 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.


Code Sample, a copy-pastable example

>>> x = pd.DataFrame({"a": range(10), "b": range(10, 20), "d": ["a", "v"] * 5}, index=pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
...                              ['speed', 'weight', 'length']],
...                      codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2, 1],
...                             [0, 1, 2, 0, 1, 2, 0, 1, 2, 1]]))
>>> x
               a   b  d
lama   speed   0  10  a
       weight  1  11  v
       length  2  12  a
cow    speed   3  13  v
       weight  4  14  a
       length  5  15  v
falcon speed   6  16  a
       weight  7  17  v
       length  8  18  a
cow    weight  9  19  v
>>> x.drop(index='cow')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Users/pgali/PycharmProjects/del/venv1/lib/python3.7/site-packages/pandas/core/frame.py", line 4169, in drop
    errors=errors,
  File "/Users/pgali/PycharmProjects/del/venv1/lib/python3.7/site-packages/pandas/core/generic.py", line 3884, in drop
    obj = obj._drop_axis(labels, axis, level=level, errors=errors)
  File "/Users/pgali/PycharmProjects/del/venv1/lib/python3.7/site-packages/pandas/core/generic.py", line 3933, in _drop_axis
    indexer = ~axis.isin(labels)
  File "/Users/pgali/PycharmProjects/del/venv1/lib/python3.7/site-packages/pandas/core/indexes/multi.py", line 3600, in isin
    values = MultiIndex.from_tuples(values, names=self.names)._values
  File "/Users/pgali/PycharmProjects/del/venv1/lib/python3.7/site-packages/pandas/core/indexes/multi.py", line 501, in from_tuples
    arrays = list(lib.tuples_to_object_array(tuples).T)
  File "pandas/_libs/lib.pyx", line 2471, in pandas._libs.lib.tuples_to_object_array
TypeError: Expected tuple, got str

Problem description

I'd expected drop to drop all the rows with cow as an index.

Expected Output

>>> x.drop(index='cow')
               a   b  d
lama   speed   0  10  a
       weight  1  11  v
       length  2  12  a
falcon speed   6  16  a
       weight  7  17  v
       length  8  18  a

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 2a7d332
python : 3.7.3.final.0
python-bits : 64
OS : Darwin
OS-release : 19.6.0
Version : Darwin Kernel Version 19.6.0: Thu Jun 18 20:49:00 PDT 2020; root:xnu-6153.141.1~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : en_US.UTF-8
pandas : 1.1.2
numpy : 1.17.3
pytz : 2020.1
dateutil : 2.8.1
pip : 20.1.1
setuptools : 49.1.0
Cython : None
pytest : None
hypothesis : 5.29.0
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
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
pytables : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

@galipremsagar galipremsagar added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 11, 2020
@phofl
Copy link
Member

phofl commented Sep 12, 2020

Hi,

thanks for your report. You have to specify a level, when dropping parts of a Multiindex or give a list of tuples (lenght of tuples must match number of levels in MultiIndex).

We could improve the error reporting here.

@phofl phofl added Docs Error Reporting Incorrect or improved errors from pandas and removed Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Sep 12, 2020
@kamahmad
Copy link

@MarcoGorelli @phofl Can I please work on this issue? Will changing the exception message fix this issue?

@leonarduschen
Copy link
Contributor

@phofl I just did some digging and it looks like the issue is not just an error message, but rather the behavior when there is an index duplicate (notice cow is a duplicate). When there is no duplicate, dropping without specifying level works just fine. For example:

df = pd.DataFrame(
    data=zip(range(9), range(10, 19)),
    columns=['a', 'COL'],
    index=pd.MultiIndex(
        levels=[['lama', 'cow', 'falcon'], ['speed', 'weight', 'length']],
        codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]]
        )
    )
print(df)
print(df.drop(index='lama'))

yields

               a  COL
lama   speed   0   10
       weight  1   11
       length  2   12
cow    speed   3   13
       weight  4   14
       length  5   15
falcon speed   6   16
       weight  7   17
       length  8   18
##########################
               a  COL
cow    speed   3   13
       weight  4   14
       length  5   15
falcon speed   6   16
       weight  7   17
       length  8   18

Is this really the intended behavior?

@phofl
Copy link
Member

phofl commented Sep 12, 2020

Interesting, thanks very much. Don‘t knoww what the intended behavior is then

@phofl
Copy link
Member

phofl commented Sep 12, 2020

Looked into it again:

We use https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.isin.html when the index is not unique. Isin can not handle strings as input, because it creates a MultiIndex from the given inputs.

When the index is unique, we use drop, which can handle strings as input.

Part starts here:

if axis.is_unique:

Is this behavior intended or should we search for a solution which is consisten between non unique and unique MultiIndexes?

@phofl phofl added MultiIndex Needs Discussion Requires discussion from core team before further action and removed Error Reporting Incorrect or improved errors from pandas good first issue labels Sep 12, 2020
@phofl phofl mentioned this issue Sep 13, 2020
1 task
@jreback jreback added this to the 1.3 milestone Dec 12, 2020
@jreback jreback added Reshaping Concat, Merge/Join, Stack/Unstack, Explode and removed Docs Needs Discussion Requires discussion from core team before further action labels Dec 12, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
MultiIndex Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Projects
None yet
6 participants