Skip to content

BUG: Cannot convert from object numeric strings to Float64Dtype #40729

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
tamargrey opened this issue Apr 1, 2021 · 3 comments · Fixed by #48205
Closed

BUG: Cannot convert from object numeric strings to Float64Dtype #40729

tamargrey opened this issue Apr 1, 2021 · 3 comments · Fixed by #48205
Assignees
Labels
Dtype Conversions Unexpected or buggy dtype conversions good first issue NA - MaskedArrays Related to pd.NA and nullable extension arrays Needs Tests Unit test(s) needed to prevent regressions

Comments

@tamargrey
Copy link

tamargrey commented Apr 1, 2021

Code Sample, a copy-pastable example

import pandas as pd

series = pd.Series(['1', '2', '3', '4'], dtype='object')
series.astype(pd.Float64Dtype())

the above produces a TypeError: object cannot be converted to a FloatingDtype:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-a9dee24fff9e> in <module>
     15 assert series.astype('float64').dtype == 'float64'
     16 # TypeError: object cannot be converted to a FloatingDtype - same for DataFrames
---> 17 series.astype(pd.Float64Dtype())
     18 

~/.pyenv/versions/3.8.2/envs/woodwork/lib/python3.8/site-packages/pandas/core/generic.py in astype(self, dtype, copy, errors)
   5875         else:
   5876             # else, only a single dtype is given
-> 5877             new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors)
   5878             return self._constructor(new_data).__finalize__(self, method="astype")
   5879 

~/.pyenv/versions/3.8.2/envs/woodwork/lib/python3.8/site-packages/pandas/core/internals/managers.py in astype(self, dtype, copy, errors)
    629         self, dtype, copy: bool = False, errors: str = "raise"
    630     ) -> "BlockManager":
--> 631         return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
    632 
    633     def convert(

~/.pyenv/versions/3.8.2/envs/woodwork/lib/python3.8/site-packages/pandas/core/internals/managers.py in apply(self, f, align_keys, ignore_failures, **kwargs)
    425                     applied = b.apply(f, **kwargs)
    426                 else:
--> 427                     applied = getattr(b, f)(**kwargs)
    428             except (TypeError, NotImplementedError):
    429                 if not ignore_failures:

~/.pyenv/versions/3.8.2/envs/woodwork/lib/python3.8/site-packages/pandas/core/internals/blocks.py in astype(self, dtype, copy, errors)
    671             vals1d = values.ravel()
    672             try:
--> 673                 values = astype_nansafe(vals1d, dtype, copy=True)
    674             except (ValueError, TypeError):
    675                 # e.g. astype_nansafe can fail on object-dtype of strings

~/.pyenv/versions/3.8.2/envs/woodwork/lib/python3.8/site-packages/pandas/core/dtypes/cast.py in astype_nansafe(arr, dtype, copy, skipna)
   1017     # dispatch on extension dtype if needed
   1018     if is_extension_array_dtype(dtype):
-> 1019         return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy)
   1020 
   1021     if not isinstance(dtype, np.dtype):

~/.pyenv/versions/3.8.2/envs/woodwork/lib/python3.8/site-packages/pandas/core/arrays/floating.py in _from_sequence(cls, scalars, dtype, copy)
    278         cls, scalars, *, dtype=None, copy: bool = False
    279     ) -> "FloatingArray":
--> 280         values, mask = coerce_to_array(scalars, dtype=dtype, copy=copy)
    281         return FloatingArray(values, mask)
    282 

~/.pyenv/versions/3.8.2/envs/woodwork/lib/python3.8/site-packages/pandas/core/arrays/floating.py in coerce_to_array(values, dtype, mask, copy)
    160             "mixed-integer-float",
    161         ]:
--> 162             raise TypeError(f"{values.dtype} cannot be converted to a FloatingDtype")
    163 
    164     elif is_bool_dtype(values) and is_float_dtype(dtype):

TypeError: object cannot be converted to a FloatingDtype

Problem description

With float64, this conversion works, and as the series' dtype would get inferred as object even if no dtype was specified, it is unexpected to me that we would not be able to convert to the Float64Dtype from that.

Expected Output

pd.Series([1.0, 2.0, 3.0, 4.0], dtype=Float64Dtype) 

Output of pd.show_versions()

INSTALLED VERSIONS

commit : f2c8480
python : 3.8.2.final.0
python-bits : 64
OS : Darwin
OS-release : 19.6.0
Version : Darwin Kernel Version 19.6.0: Sun Jul 5 00:43:10 PDT 2020; root:xnu-6153.141.1~9/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.2.3
numpy : 1.19.5
pytz : 2021.1
dateutil : 2.8.1
pip : 21.0.1
setuptools : 41.2.0
Cython : None
pytest : 6.0.1
hypothesis : None
sphinx : 3.2.1
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.3
IPython : 7.18.1
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : 0.8.7
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 3.0.0
pyxlsb : None
s3fs : None
scipy : 1.6.2
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

@tamargrey tamargrey added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Apr 1, 2021
@jorisvandenbossche
Copy link
Member

@tamargrey Thanks for the clear report!

Indeed, currently we seem to specifically error when trying to construct a Float64Dtype array from numeric strings. The same is true for Int64Dtype, and also when constructing directly (not through astype):

In [25]: pd.Series(['1', '2', '3', '4'], dtype='Float64')
...
TypeError: <U1 cannot be converted to a FloatingDtype

The underlying reason comes from:

if is_object_dtype(values):
inferred_type = lib.infer_dtype(values, skipna=True)
if inferred_type == "empty":
values = np.empty(len(values))
values.fill(np.nan)
elif inferred_type not in [
"floating",
"integer",
"mixed-integer",
"integer-na",
"mixed-integer-float",
]:
raise TypeError(f"{values.dtype} cannot be converted to a FloatingDtype")

where we simply disallow this.
To make this consistent with the other dtypes, we should try to convert to float in the above snippet, instead of raising an error.

Contributions always welcome!


A possible workaround for now is to first convert to String dtype, and then the conversion to Float64 works:

In [26]: pd.Series(['1', '2', '3', '4'], dtype='object').astype("string").astype("Float64")
Out[26]: 
0    1.0
1    2.0
2    3.0
3    4.0
dtype: Float64

@jorisvandenbossche jorisvandenbossche added NA - MaskedArrays Related to pd.NA and nullable extension arrays and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Apr 1, 2021
@jorisvandenbossche jorisvandenbossche added this to the Contributions Welcome milestone Apr 1, 2021
junjunjunk added a commit to junjunjunk/pandas that referenced this issue Apr 3, 2021
junjunjunk added a commit to junjunjunk/pandas that referenced this issue Apr 3, 2021
junjunjunk added a commit to junjunjunk/pandas that referenced this issue Apr 3, 2021
@mroeschke mroeschke added the Dtype Conversions Unexpected or buggy dtype conversions label Aug 19, 2021
@phofl
Copy link
Member

phofl commented Aug 14, 2022

This works now, may need tests

@phofl phofl added good first issue Needs Tests Unit test(s) needed to prevent regressions and removed Bug labels Aug 14, 2022
@srotondo
Copy link
Contributor

take

srotondo pushed a commit to srotondo/pandas that referenced this issue Aug 23, 2022
srotondo pushed a commit to srotondo/pandas that referenced this issue Aug 23, 2022
mroeschke pushed a commit that referenced this issue Aug 26, 2022
* TST: Wrote test for Float64 conversion #40729

* TST: Moved test #40729

Co-authored-by: Steven Rotondo <[email protected]>
noatamir pushed a commit to noatamir/pandas that referenced this issue Nov 9, 2022
…8205)

* TST: Wrote test for Float64 conversion pandas-dev#40729

* TST: Moved test pandas-dev#40729

Co-authored-by: Steven Rotondo <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Dtype Conversions Unexpected or buggy dtype conversions good first issue NA - MaskedArrays Related to pd.NA and nullable extension arrays Needs Tests Unit test(s) needed to prevent regressions
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants