Skip to content
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

BUG: Converting NumPy-nullable dtypes to str #60123

Closed
2 of 3 tasks
pkludig opened this issue Oct 29, 2024 · 10 comments
Closed
2 of 3 tasks

BUG: Converting NumPy-nullable dtypes to str #60123

pkludig opened this issue Oct 29, 2024 · 10 comments
Labels
Docs PDEP missing values Issues that would be addressed by the Ice Cream Agreement from the Aug 2023 sprint Strings String extension data type and string data

Comments

@pkludig
Copy link

pkludig commented Oct 29, 2024

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

pd.DataFrame(
    {
        "a": [1, 2, None]
    },
    dtype="Int64"
).astype(str).astype("Int64")

Issue Description

When casting an Int64 NA-Value to a string it returns <NA> which is not well interpretable as a missing value for anything. It even fails in converting it back to an Int64 value.

Expected Behavior

Int64 NA-Values should be casted to None when casted to String, as this is the equivalent represantation in a string-column, similar to being convertet to a float NaN for float, which is also shown by the following example, which works:

import pandas as pd

pd.DataFrame(
    {
        "a": [1, 2, None]
    },
    dtype="Int64"
).astype(str).replace("<NA>", None).astype("Int64")

Installed Versions

INSTALLED VERSIONS

commit : bdc79c1
python : 3.10.12.final.0
python-bits : 64
OS : Linux
OS-release : 6.8.0-47-generic
Version : #47~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Oct 2 16:16:55 UTC 2
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : en_US.UTF-8
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.2.1
numpy : 1.26.4
pytz : 2024.1
dateutil : 2.9.0.post0
setuptools : 69.0.3
pip : 24.0
Cython : None
pytest : 8.2.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.3
IPython : 8.22.2
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.12.3
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.5
pandas_gbq : None
pyarrow : 15.0.2
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : 2.0.28
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2024.1
qtpy : None
pyqt5 : None

@pkludig pkludig added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Oct 29, 2024
@rhshadrach rhshadrach added PDEP pandas enhancement proposal PDEP missing values Issues that would be addressed by the Ice Cream Agreement from the Aug 2023 sprint and removed Needs Triage Issue that has not been reviewed by a pandas team member PDEP pandas enhancement proposal labels Oct 29, 2024
@rhshadrach
Copy link
Member

Thanks for the report. If we were to change this and be consistent, I think it would have to impact more than just the Numpy-nullable dtypes:

print(pd.DataFrame({"a": [1.0, 2.0, np.nan]}).astype("str"))
#      a
# 0  1.0
# 1  2.0
# 2  nan

In addition, it does already work with "string":

print(pd.DataFrame({"a": [1, 2, pd.NA]}, dtype="Int64").astype("string").astype("Int64"))
#       a
# 0     1
# 1     2
# 2  <NA>

Does this work for your use case?

I believe .astype(str) gives the string representation in general, which seems to me to be a reasonable behavior. Even if we do prefer None, I think changing this would be too disruptive. Given that we want to start moving users to "string" (and even, "string[pyarrow]"), my opinion is this should remain as-is.

@rhshadrach rhshadrach added the Closing Candidate May be closeable, needs more eyeballs label Oct 29, 2024
@rhshadrach rhshadrach changed the title BUG: BUG: Converting NumPy-nullable dtypes to str Oct 29, 2024
@pkludig
Copy link
Author

pkludig commented Oct 29, 2024

In general, using "string" instead will work, so thank you for that. However, this behavior is unexpected at first and I can't fin a place where it's documented. So maybe it would be helpful to document that somewhere (if there isn't already something) and link it to the astype docu page, so it will actually be found when searching for this kind of problem?

@rhshadrach
Copy link
Member

Agreed this would be good to document in the astype docstring. Contributions welcome!

@rhshadrach rhshadrach added Docs Strings String extension data type and string data and removed Closing Candidate May be closeable, needs more eyeballs Bug labels Oct 29, 2024
@ZKaoChi
Copy link
Contributor

ZKaoChi commented Oct 30, 2024

Whether it's None, np.nan, or pd.NA, they will all be converted to pd.NA in the end, so I'll just use pd.NA as an example.
I've found that once the conversion goes through "str", it gets an error, even though it doesn't end up being converted from "str" to "int64".

print(pd.DataFrame({"a": [1, 2, pd.NA]}, dtype="Int64").astype("str").astype("string").astype("Int64"))
# ValueError: invalid literal for int() with base 10: '<NA>'

It looks like "str" is doing some damage to the data structure, so it may be necessary to change more than just astpye doc.

@jorisvandenbossche
Copy link
Member

I actually recently changed this on the main branch for the future string dtype, and so this behaviour will be changed/fixed in pandas 3.0.
See the "astype(str) preserving missing values (no longer converting NaN to a string "nan")" section in the top post of #59328, and the older issue #25353 that discussed this as well.

I believe .astype(str) gives the string representation in general, which seems to me to be a reasonable behavior.

With str becoming an alias of the future string dtype, this now behaves similarly as astype("string") in preserving missing values.

@rhshadrach
Copy link
Member

I actually recently changed this on the main branch for the future string dtype, and so this behaviour will be changed/fixed in pandas 3.0.

With str becoming an alias of the future string dtype, this now behaves similarly as astype("string") in preserving missing values.

I am not seeing either of these on main.

@jorisvandenbossche
Copy link
Member

The alias only works if the future option is enabled:

In [2]: pd.options.future.infer_string = True

In [3]: pd.DataFrame(
   ...:     {
   ...:         "a": [1, 2, None]
   ...:     },
   ...:     dtype="Int64"
   ...: ).astype(str)
Out[3]: 
     a
0    1
1    2
2  NaN

and so because in the above it is still an actual missing values and not a string, converting back to Int64 also works (the original example in the OP):

In [4]: pd.DataFrame(
   ...:     {
   ...:         "a": [1, 2, None]
   ...:     },
   ...:     dtype="Int64"
   ...: ).astype(str).astype("Int64")
Out[4]: 
      a
0     1
1     2
2  <NA>

@rhshadrach
Copy link
Member

The alias only works if the future option is enabled

Ah, thanks! I was thinking this was already enabled by default on main.

@rhshadrach
Copy link
Member

I think everything is resolved here for 3.0. Closing.

@jorisvandenbossche
Copy link
Member

jorisvandenbossche commented Oct 30, 2024

I was thinking this was already enabled by default on main.

Yeah, it's not yet. I was thinking to switch that once 2.3 is out (and most of the backports are done)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Docs PDEP missing values Issues that would be addressed by the Ice Cream Agreement from the Aug 2023 sprint Strings String extension data type and string data
Projects
None yet
Development

No branches or pull requests

4 participants