13

The warning in the title is produced by pandas 0.21.0 on Python 3.6.3 with code such as pd.Series(["a", "b", "b"]).astype("category", categories = ["a", "b", "c"]). How exactly is one supposed to write this now?

3 Answers 3

17

The CategoricalDtype mentioned in the warning is available as pd.api.types.CategoricalDtype. So, you can write pd.Series(["a", "b", "b"]).astype(pd.api.types.CategoricalDtype(categories = ["a", "b", "c"])).

2
  • 4
    don't understand why it was made more complicated/longish? Commented Sep 6, 2018 at 5:40
  • 3
    @randomSampling Yes, it's poor design.
    – Ted Petrou
    Commented Dec 10, 2018 at 3:22
4
pd.Categorical(pd.Series(['a','b','b']), categories = ['a', 'b', 'c'])

Also you can use the ordered parameter to create a categorical hierarchy

result = pd.Categorical(pd.Series(['a','b','b']), categories = ['a', 'b', 'c'], ordered = True)

Update to convert to Series dtype

pd.Series(result)
2
  • This code creates a Categorical object, not a Series with a Categorical dtype. Commented Sep 30, 2018 at 11:39
  • You are right. Set above equal to result and convert to series with pd.Series(result)
    – dernk
    Commented Sep 30, 2018 at 21:01
1

I much prefer the lack of repetition in the following:

s = pd.Series(["a", "b", "b"]).astype("category").cat.as_ordered()

And prove it

s.max()

doesn't generate an exception.

(It will in recent pandas if not orderred.)

1
  • But then you can't specify the categories, as you can in the original code. Commented Sep 8, 2023 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.