Index.astype('category') does not work · Issue #20843 · pandas-dev/pandas (original) (raw)
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'
.
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