Skip to content

BUG: scalar getitem indexing with CategoricalIndex #16131

Closed
@jorisvandenbossche

Description

@jorisvandenbossche

Scalar __getitem__ indexing with a CategoricalIndex gives a KeyError (example with two different types of categoricals):

In [46]: cats = pd.Categorical(['a', 'b'])

In [47]: s = pd.Series([1, 2], index=cats)

In [48]: s[cats[0]]
...
KeyError: 'a'

In [49]: s.loc[cats[0]]
Out[49]: 1

In [50]: cats = pd.Categorical([pd.Timestamp('12-31-1999'),pd.Timestamp('12-31-2000')])

In [51]: s = pd.Series([1, 2], index=cats)

In [52]: s[cats[0]]
...
KeyError: Timestamp('1999-12-31 00:00:00')

In [53]: s.loc[cats[0]]
Out[53]: 1

so with loc it works correctly, as well as when passing a list to [] (after #16115 is fixed)

__getitem__ on the columns works correctly:

In [55]: df = pd.DataFrame([[1, 2], [3, 4]], columns=cats)

In [56]: df[cats[0]]
Out[56]: 
0    1
1    3
Name: 1999-12-31 00:00:00, dtype: int64

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugCategoricalCategorical Data TypeIndexingRelated to indexing on series/frames, not to indexes themselves

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions