Skip to content

BUG: StringArray.astype() raises for datetime, period, boolean & timedelta with missing values #40566

Open
@siboehm

Description

@siboehm
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import pandas as pd
s = pd.Series(["2020-10-10", None], dtype="string")
s.astype("datetime64[ns]") # fails

s = pd.Series(["1 Day", None], dtype="string")
s.astype("timedelta64[ns]") # fails

s = pd.Series(["1/1/2021", None], dtype="string")
s.astype("period[M]") # fails

s = pd.Series([True, None], dtype="string")
s.astype("boolean") # fails

Similar issue for timedelta64 raised by jbrockmendel in #38509.

Problem description

The behaviour looks like a bug and I'd like to help out, however the astype dispatching (#22384) and the _from_sequence specifics (#33254) seem to be debated issues.

If you'd like I can write a PR that fixes this by:

  1. implementing _from_sequence_of_strings in the ExtensionArrays where it hasn't been implemented: Categorical, DatetimeArray, TimedeltaArray.
  2. in StringArray.astype() convert to ExtensionArrayDTypes using _from_sequence_of_strings instead of _from_sequence.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : f2c8480
python : 3.8.6.final.0
python-bits : 64
OS : Linux
OS-release : 5.8.0-45-generic
Version : #51-Ubuntu SMP Fri Feb 19 13:24:51 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.2.3
numpy : 1.19.2
pytz : 2020.5
dateutil : 2.8.1
pip : 21.0.1
setuptools : 52.0.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.8.5 (dt dec pq3 ext lo64)
jinja2 : None
IPython : 7.19.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : 0.8.7
fastparquet : None
gcsfs : None
matplotlib : 3.3.4
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 3.0.0
pyxlsb : None
s3fs : None
scipy : 1.6.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None
None

Metadata

Metadata

Assignees

No one assigned

    Labels

    AstypeBugDtype ConversionsUnexpected or buggy dtype conversionsExtensionArrayExtending pandas with custom dtypes or arrays.StringsString 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