Skip to content

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

Closed
@tamargrey

Description

@tamargrey

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

Metadata

Metadata

Assignees

Labels

Dtype ConversionsUnexpected or buggy dtype conversionsNA - MaskedArraysRelated to pd.NA and nullable extension arraysNeeds TestsUnit test(s) needed to prevent regressionsgood first issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions