Skip to content

DataFrame.stack() needs to accept list for level argument #489

@Dr-Irv

Description

@Dr-Irv

Describe the bug

For DataFrame.stack(), level is allowed to be a list

To Reproduce

  1. Provide a minimal runnable pandas example that is not properly checked by the stubs.
import pandas as pd
multicol2 = pd.MultiIndex.from_tuples([('weight', 'kg'),
                                       ('height', 'm')])
df_multi_level_cols2 = pd.DataFrame([[1.0, 2.0], [3.0, 4.0]],
                                    index=['cat', 'dog'],
                                    columns=multicol2)
df_multi_level_cols2.stack([0, 1])
  1. Indicate which type checker you are using (mypy or pyright).

pyright 1.1.286

  1. Show the error message received from that type checker while checking your example.
    pyright reports:
stack.py:7:28 - error: Argument of type "list[int]" cannot be assigned to parameter "level" of type "Level" in function "stack"
    Type "list[int]" cannot be assigned to type "Level"
      "list[int]" is incompatible with protocol "Hashable"
        "__hash__" is an incompatible type
          Type "None" cannot be assigned to type "(self: list[int]) -> int"
      "list[int]" is incompatible with "int" (reportGeneralTypeIssues)

Please complete the following information:

  • OS: Windows 10
  • OS Version: 10
  • python version: 3.9
  • version of type checker: pyright 1.1.286
  • version of installed pandas-stubs 1.5.2.221213

Additional context

Change

def stack(self, level: Level = ..., dropna: _bool = ...) -> DataFrame | Series: ...

to allow Level | list[Level] for the level argument.

PR welcome with tests

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions