Skip to content

BUG: undocumented astype("category").astype(str) type inconsistency between pandas 1.1 & 1.2 #41797

Closed
@timlod

Description

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

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

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

import numpy as np
import pandas as pd

print(pd.__version__)
df = pd.DataFrame(["a", "b", np.nan])
print("astype(str): \n", df.astype(str))
print("astype('category').astype(str): \n", df.astype("category").astype(str))

Output 1.1.3:

1.1.3
astype(str): 
      0
0    a
1    b
2  nan
astype('category').astype(str): 
      0
0    a
1    b
2  nan

Output 1.2.4:

1.2.4
astype(str): 
      0
0    a
1    b
2  nan
astype('category').astype(str): 
      0
0    a
1    b
2  NaN

Problem description

The above snippet run on version 1.1 (tested on 1.1.3) returns 'nan' strings of the converted categories, whereas on 1.2 (tested on 1.2.4) keeps np.nan objects. Tangentially, when using the pandas StringDtype conversion (.astype("string"), pandas 1.1 and 1.2 both keep a NAType after conversion from categorical to string.

It is not clear whether it is expected behaviour that this conversion keeps np.nan, or whether it should return a 'nan' string. The former would mean that this is now correct, the latter would mean there is a regression.

This issue is probably related to #37355 and #25353

Expected Output

Document what behaviour is desired.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 2cb9652
python : 3.8.2.final.0
python-bits : 64
OS : Linux
OS-release : 4.19.0-14-amd64
Version : #1 SMP Debian 4.19.171-2 (2021-01-30)
machine : x86_64
processor :
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.2.4
numpy : 1.20.2
pytz : 2021.1
dateutil : 2.8.1
pip : 21.1.2
setuptools : 54.2.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.3
IPython : 7.22.0
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
fsspec : 0.8.7
fastparquet : None
gcsfs : None
matplotlib : 3.4.1
numexpr : None
odfpy : None
openpyxl : 3.0.7
pandas_gbq : None
pyarrow : 4.0.0
pyxlsb : None
s3fs : None
scipy : 1.6.2
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : 2.0.1
xlwt : None
numba : 0.53.1

Versions are identical except for one run at pandas 1.1.3, the other at 1.2.4.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugCategoricalCategorical Data TypeRegressionFunctionality that used to work in a prior pandas version

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions