Pandas version checks

  • [X] I have checked that this issue has not already been reported.

  • [X] I have confirmed this bug exists on the latest version of pandas.

  • [ ] I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd 

double_cats = pd.Series([1.2, 2.3, 3.9, 4.1, 5.5], dtype="category")
explicit_dtype = pd.CategoricalDtype(
            categories=double_cats.dtype.categories.astype("string").astype("object"),
        )

all_nans = double_cats.astype(explicit_dtype)
assert all(all_nans.isna())

Issue Description

I need to convert a category dtype's float categories to be string categories with the object dtype. So turn pd.Series([1.2, 2.3, 3.9, 4.1, 5.5], dtype="category") into pd.Series(['1.2', '2.3', '3.9', '4.1', '5.5'], dtype="object").

Other than multiple chained astype calls to first convert the data to be string and then object and then category again, the best way I found to change the dtype of a category dtype's categories is to set it directly on a new pd.CategoricalDtype object and then call astype once. But it turns out doing that nullifies all the values of my data, so I'm stuck with the chained astype calls for now, which I assume is slower.

It seems pretty clear that the result of the above snippet should not be to nullify all values, so this ticket is to track a fix for that bug, but I'd also be open towards any other workarounds in the mean time. Thanks!

Expected Behavior

The behavior should match that of chained astype calls directly on the data:

import pandas as pd 

double_cats = pd.Series([1.2, 2.3, 3.9, 4.1, 5.5], dtype="category")

no_nans = double_cats.astype("string").astype("object").astype("category")
assert not any(no_nans.isna())

The result should be the same as if we started with string categories

    double_cats = pd.Series(['1.2', '2.3', '3.9', '4.1', '5.5'], dtype="category")
    explicit_dtype = pd.CategoricalDtype(
                categories=double_cats.dtype.categories.astype("object"),
            )

    result = double_cats.astype(explicit_dtype)

Installed Versions

INSTALLED VERSIONS ------------------ commit : 2e218d10984e9919f0296931d92ea851c6a6faf5 python : 3.8.2.final.0 python-bits : 64 OS : Darwin OS-release : 21.6.0 Version : Darwin Kernel Version 21.6.0: Wed Aug 10 14:25:27 PDT 2022; root:xnu-8020.141.5~2/RELEASE_X86_64 machine : x86_64 processor : i386 byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8 pandas : 1.5.3 numpy : 1.22.4 pytz : 2022.2.1 dateutil : 2.8.2 setuptools : 59.8.0 pip : 22.2.2 Cython : 0.29.32 pytest : 7.1.2 hypothesis : None sphinx : 4.5.0 blosc : None feather : None xlsxwriter : None lxml.etree : 4.9.1 html5lib : None pymysql : None psycopg2 : None jinja2 : 3.1.2 IPython : 8.5.0 pandas_datareader: None bs4 : 4.11.1 bottleneck : None brotli : None fastparquet : None fsspec : 2022.8.2 gcsfs : None matplotlib : 3.5.3 numba : 0.56.2 numexpr : None odfpy : None openpyxl : None pandas_gbq : None pyarrow : None pyreadstat : None pyxlsb : None s3fs : None scipy : 1.8.1 snappy : None sqlalchemy : None tables : None tabulate : None xarray : None xlrd : None xlwt : None zstandard : None tzdata : None

Comment From: rhshadrach

In general when a value does not appear in the categories, the categorical dtype turns it into null. Your values are floats, your categories are Python strings. It sounds like you're asking for an implicit cast, is that right?

Comment From: tamargrey

Ah, I see what you're getting at and that just having double_cats.astype("string") in the explicit dtype is what is turning everything to nans.

What I primarily need here is the ability to change the dtype of a categorical column's categories. In the example in this ticket, I was assuming that in explicitly creating a CategoricalDtype with my desired category dtypes and assigning it to preexisting data there would be some amount of implicit casting to recognize that the categories were the same. But of course 1.1 isn't equal to "1.1" in python.

Is chaining .astype("string").astype("object").astype("category") on the original going to be my best bet to get that categories dtype change?

Comment From: rhshadrach

You can do .apply(str) instead. From some testing this seems to be about twice as fast.

Comment From: phofl

Closing for now, this behaves as expected