Skip to content

BUG: astype("str") converts NA values to strings #44156

Closed
@alexreg

Description

@alexreg

  • 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 master branch of pandas.

Reproducible Example

import pandas as pd
import numpy as np

pd.Series(["foo", "bar", pd.NA]).astype("str") // ["foo", "bar", "<NA>"]
pd.Series(["foo", "bar", np.NaN]).astype("str") // ["foo", "bar", "nan"]
pd.Series(["foo", "bar", None]).astype("str") // ["foo", "bar", "None"]

Issue Description

NA/null values are converted to their string representation when doing .astype("str"), which seems like odd/undesirable behaviour.

Expected Behavior

import pandas as pd
import numpy as np

pd.Series(["foo", "bar", pd.NA]).astype("str") // ["foo", "bar", pd.NA]
pd.Series(["foo", "bar", np.NaN]).astype("str") // ["foo", "bar", np.NaN]
pd.Series(["foo", "bar", None]).astype("str") // ["foo", "bar", None]

Installed Versions

INSTALLED VERSIONS

commit : 9b2bb73
python : 3.9.7.final.0
python-bits : 64
OS : Darwin
OS-release : 20.6.0
Version : Darwin Kernel Version 20.6.0: Wed Jun 23 00:26:31 PDT 2021; root:xnu-7195.141.2~5/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8

pandas : 1.4.0.dev0+952.g9b2bb732f0
numpy : 1.21.3
pytz : 2021.3
dateutil : 2.8.2
pip : 21.3
setuptools : 58.2.0
Cython : 0.29.24
pytest : 6.2.5
hypothesis : 6.23.4
sphinx : 4.2.0
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.6.3
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 3.0.2
IPython : None
pandas_datareader: None
bs4 : 4.10.0
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : 3.0.9
pandas_gbq : None
pyarrow : 5.0.0
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : 0.8.9
xarray : None
xlrd : 2.0.1
xlwt : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    AstypeBugDtype ConversionsUnexpected or buggy dtype conversionsMissing-datanp.nan, pd.NaT, pd.NA, dropna, isnull, interpolateNA - MaskedArraysRelated to pd.NA and nullable extension arraysStringsString extension data type and string data

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions