Skip to content

Why does df.loc[] reject lists of MultiIndex-iteration results? #1153

@glatterf42

Description

@glatterf42

Hi there :)
Thanks for your continued work and releasing v2.2.3.250308! Unfortunately, this release produced an error in our "Code Quality" CI checks: on code that is working as intended, mypy is now complaining about the type of an argument to df.loc[].
I have summarized the issue here and you can find today's CI failure here.

Describe the bug
When iterating over a MultiIndex and passing each iteration item to another function that uses it in a df.loc[] call like df.loc[[index]], mypy complains that the index type is invalid. This depends on the type hint of the function, of course, but the type of index is revealed to me as tuple and when I use this as the type hint, mypy complains.

To Reproduce
Here's a minimal working example:

import pandas as pd

df = pd.DataFrame(
    {"foo": [1, 2, 3], "bar": ["one", "two", "three"], "baz": [1.0, 2.0, 3.0]}
).set_index(["foo", "bar"])


def test_function(test_df: pd.DataFrame, index: tuple) -> None:
    print(test_df.loc[[index]])

for i in df.index:
    test_function(df, i)

Executing this prints

         baz
foo bar     
1   one  1.0
         baz
foo bar     
2   two  2.0
           baz
foo bar       
3   three  3.0

But running mypy on this yields

error: Invalid index type "list[tuple[Any, ...]]" for "_LocIndexerFrame[DataFrame]"; expected type "slice[Any, Any, Any] | ndarray[Any, dtype[integer[Any]]] | Index[Any] | list[int] | Series[int] | <6 more items>"  [index]

Please complete the following information:

  • OS: Linux (Ubuntu 24.04.2 LTS)
  • Python 3.12.3
  • Mypy 1.15.0
  • pandas-stubs 2.2.3.250308
  • pandas 2.2.3

Additional context
Maybe a better title for the question would be: how should I type hint index so that mypy is happy?

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