Skip to content

Index.droplevel() should not be permitted #1678

@Dr-Irv

Description

@Dr-Irv

Describe the bug
Index.droplevel() is not supported.

So if a user knows that they have a MultiIndex (e.g., df.index.droplevel(), they should be forced to do a cast.

To Reproduce

>>> import pandas as pd
>>> df = pd.DataFrame({"x":[1,2]})
>>> df
   x
0  1
1  2
>>> df.columns.droplevel([0])
Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    df.columns.droplevel([0])
    ~~~~~~~~~~~~~~~~~~~~^^^^^
  File "C:\Condadirs\envs\base313\Lib\site-packages\pandas\core\indexes\base.py", line 2301, in droplevel
    return self._drop_level_numbers(levnums)
           ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^
  File "C:\Condadirs\envs\base313\Lib\site-packages\pandas\core\indexes\base.py", line 2312, in _drop_level_numbers
    raise ValueError(
    ...<2 lines>...
    )
ValueError: Cannot remove 1 levels from an index with 1 levels: at least one level must be left.

So it doesn't work at runtime

Please complete the following information:

  • OS: Windows 11
  • OS Version 2H25
  • python version 3.13
  • version of type checker pyright 1.1.408 - it allows the above
  • version of installed pandas-stubs - dev version

Additional context

We could not fix this because it forces a cast if you do something like this. But I think this is helpful to users to make them acknowledge that the corresponding index is a MultiIndex

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions