Skip to content

Mixed object array with astype to Extension Array throws TypeError #34460

Open
@WillAyd

Description

@WillAyd

This works

>>> pd.Series([1, "1"]).astype(int)
0    1
1    1
dtype: int64

This doesn't

>>> pd.Series([1, "1"]).astype("Int64")
Traceback (most recent call last):
  File "/Users/willayd/clones/pandas/pandas/core/arrays/integer.py", line 165, in safe_cast
    return values.astype(dtype, casting="safe", copy=copy)
TypeError: Cannot cast array from dtype('O') to dtype('int64') according to the rule 'safe'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/willayd/clones/pandas/pandas/core/generic.py", line 5635, in astype
    new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors,)
  File "/Users/willayd/clones/pandas/pandas/core/internals/managers.py", line 573, in astype
    return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
  File "/Users/willayd/clones/pandas/pandas/core/internals/managers.py", line 402, in apply
    applied = getattr(b, f)(**kwargs)
  File "/Users/willayd/clones/pandas/pandas/core/internals/blocks.py", line 581, in astype
    values = astype_nansafe(vals1d, dtype, copy=True)
  File "/Users/willayd/clones/pandas/pandas/core/dtypes/cast.py", line 912, in astype_nansafe
    return dtype.construct_array_type()._from_sequence(arr, dtype=dtype, copy=copy)
  File "/Users/willayd/clones/pandas/pandas/core/arrays/integer.py", line 362, in _from_sequence
    return integer_array(scalars, dtype=dtype, copy=copy)
  File "/Users/willayd/clones/pandas/pandas/core/arrays/integer.py", line 153, in integer_array
    values, mask = coerce_to_array(values, dtype=dtype, copy=copy)
  File "/Users/willayd/clones/pandas/pandas/core/arrays/integer.py", line 270, in coerce_to_array
    values = safe_cast(values, dtype, copy=False)
  File "/Users/willayd/clones/pandas/pandas/core/arrays/integer.py", line 172, in safe_cast
    raise TypeError(
TypeError: cannot safely cast non-equivalent object to int64

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions