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
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"]))
.
-
4don't understand why it was made more complicated/longish? Commented Sep 6, 2018 at 5:40
-
3
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)
-
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)– dernkCommented Sep 30, 2018 at 21:01
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.)
-
But then you can't specify the categories, as you can in the original code. Commented Sep 8, 2023 at 11:30