Skip to content

Index.astype('category') does not work #20843

Closed
@h-vetinari

Description

@h-vetinari

It's easy to make a Series categorical by using .astype('category'), and this yields the same result as calling the constructor with dtype='category'.

The same call fails for Index:

s = pd.Series(['a', 'b', 'a'])
sc = pd.Series(['a', 'b', 'a'], dtype='category')
s.astype('category')
# 0    a
# 1    b
# 2    a
# dtype: category
# Categories (2, object): [a, b]

# # both ways yield the same result
sc.equals(s.astype('category'))
# True

# # For Index ...
t = pd.Index(s.values)
t
# Index(['a', 'b', 'a'], dtype='object')
# # ... the direct constructor works
tc = pd.Index(['a', 'b', 'a'], dtype='category')
# # ... but not the conversion
t.astype('category')
# TypeError: data type "category" not understood

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