Skip to content

BUG: Setting CategoricalDtype categories as string objects nulls out data #51074

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
2 of 3 tasks
tamargrey opened this issue Jan 30, 2023 · 4 comments
Closed
2 of 3 tasks
Labels
Bug Categorical Categorical Data Type Closing Candidate May be closeable, needs more eyeballs Dtype Conversions Unexpected or buggy dtype conversions

Comments

@tamargrey
Copy link

Pandas version checks

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

  • 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 : 2e218d1
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

@tamargrey tamargrey added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 30, 2023
@rhshadrach
Copy link
Member

rhshadrach commented Jan 30, 2023

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?

@rhshadrach rhshadrach added Categorical Categorical Data Type Needs Info Clarification about behavior needed to assess issue Dtype Conversions Unexpected or buggy dtype conversions labels Jan 30, 2023
@tamargrey
Copy link
Author

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?

@rhshadrach
Copy link
Member

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

@rhshadrach rhshadrach added Closing Candidate May be closeable, needs more eyeballs and removed Needs Info Clarification about behavior needed to assess issue Needs Triage Issue that has not been reviewed by a pandas team member labels Feb 1, 2023
@phofl
Copy link
Member

phofl commented Feb 6, 2023

Closing for now, this behaves as expected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Categorical Categorical Data Type Closing Candidate May be closeable, needs more eyeballs Dtype Conversions Unexpected or buggy dtype conversions
Projects
None yet
Development

No branches or pull requests

3 participants