[Python] Why does pandas.Series allow a list as an index label (e.g. [['A'], 'B', 'C'])?

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    I accidentally created a pandas.Series using a list as part of the index, and to my surprise, it worked without any error:

    import pandas as pd

    series = pd.Series([1, 2, 3], index=[['A'], 'B', 'C'])
    print(series)
    print(type(list(series.index)[0])) # outputs: <class 'list'>


    This creates a Series object where the first index value is a Python list (['A']), , which surprised me because I assumed that all index labels in a pandas Series must be hashable types (like strings, numbers, or tuples). Lists, being mutable, are not hashable — so I expected an error.

    However, I can still print and access the Series — at least partially — without an immediate error.

    When I try this:

    series.loc[['A']]


    I get TypeError: unhashable type: 'list'

    Questions:

    • Why does pandas allow a list as an index label in the first place?
    • Is this behavior intentional or just a side effect of how Index objects are handled internally?

    I'm using pandas version 2.2.3.

    Any insights or references would be greatly appreciated!

    Continue reading...

Compartilhe esta Página