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: pd.Series fails to cast datetime series containing only NaT to timedelta type #60728

Closed
3 tasks done
Casper-Guo opened this issue Jan 17, 2025 · 9 comments · Fixed by #60882
Closed
3 tasks done
Assignees
Labels
Bug Constructors Series/DataFrame/Index/pd.array Constructors Dtype Conversions Unexpected or buggy dtype conversions

Comments

@Casper-Guo
Copy link

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

example = pd.Series(
    pd.Series([pd.NaT], dtype="datetime64[ns]"), dtype="timedelta64[ns]"
)
print(example.dtype)

Issue Description

The above snipper outputs datetime64[ns], which is against the documented behavior for pd.Series:

dtype : str, numpy.dtype, or ExtensionDtype, optional
Data type for the output Series.

Reference theOehrly/Fast-F1#674

Expected Behavior

Expect the output series example to have timedelta64[ns] data type. Or for the snippet to emit an error or warning indicating this conversion is not available.

Installed Versions

INSTALLED VERSIONS

commit : 0691c5c
python : 3.12.4
python-bits : 64
OS : Linux
OS-release : 5.15.167.4-microsoft-standard-WSL2
Version : #1 SMP Tue Nov 5 00:21:55 UTC 2024
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : C.UTF-8
LOCALE : C.UTF-8

pandas : 2.2.3
numpy : 2.0.1
pytz : 2024.1
dateutil : 2.9.0.post0
pip : 24.2
Cython : None
sphinx : None
IPython : 8.26.0
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.12.3
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
html5lib : None
hypothesis : None
gcsfs : None
jinja2 : 3.1.5
lxml.etree : None
matplotlib : 3.9.2
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : None
pyreadstat : None
pytest : 8.3.3
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.14.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2024.1
qtpy : None
pyqt5 : None

@Casper-Guo Casper-Guo added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 17, 2025
@jbrockmendel
Copy link
Member

I’d expect this to raise

@rhshadrach rhshadrach added Dtype Conversions Unexpected or buggy dtype conversions Constructors Series/DataFrame/Index/pd.array Constructors and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Jan 29, 2025
@rhshadrach
Copy link
Member

@jbrockmendel - should this raise as well?

example = pd.Series(pd.Series([1.5], dtype="float64"), dtype="int64")
print(example.dtype)
# int64

@rhshadrach rhshadrach added the Needs Discussion Requires discussion from core team before further action label Jan 29, 2025
@jbrockmendel
Copy link
Member

should this raise as well?

That's a tough one that should be out of scope here. datetime64->timedelta64 is semantic nonsense that should never work, whereas float64->int64 is "should we silently round". I think joris has an issue about "safe" casting that would be the appropriate place to discuss that.

@Casper-Guo
Copy link
Author

Casper-Guo commented Jan 31, 2025

For my planning purpose, some context about how we ran into this bug.

Old code:

laps_start_time = pd.Series(laps_start_time) # laps_start_time is a list that contains timedelta types
result['LapStartTime'] = pd.Series(laps_start_time, dtype='timedelta64[ns]')

In some cases laps_start_time = [pd.NaT] and the bug manifests since the series pick up datetime type. If it had any non-null timedelta entries then it works as expected. We fixed this with;

result['LapStartTime'] = pd.Series(laps_start_time, dtype="timedelta64[ns]")

Is there a better null representation for the timedelta type that Pandas wouldn't confuse as a datetime type?

FWIW I will prefer the other case to not raise as I am explicitly requesting a reasonable casting.

@jbrockmendel
Copy link
Member

Is there a better null representation for the timedelta type that Pandas wouldn't confuse as a datetime type?

np.timedelta64("NaT") would work. Alternatively if you know you want the output to be timedelta64 dtype, you can specify that when passing the list to the Series constructor and it will skip doing dtype inference (which always treats only-pd.NaT as datetime64, xref #24983)

Casper-Guo added a commit to Casper-Guo/Fast-F1 that referenced this issue Feb 1, 2025
@rhshadrach rhshadrach removed the Needs Discussion Requires discussion from core team before further action label Feb 2, 2025
@snitish
Copy link
Contributor

snitish commented Feb 6, 2025

It looks like the reason this conversion from datetime64 to timedelta64 doesn't raise is because it explicitly ignores errors:

data = data.astype(dtype=dtype, errors="ignore")

@jbrockmendel
Copy link
Member

Good catch. Passing errors="ignore" looks sketchy here. do any tests break if we remove that?

@snitish
Copy link
Contributor

snitish commented Feb 8, 2025

@jbrockmendel , none of the tests failed. I created a PR with the fix and added a new test.

@snitish
Copy link
Contributor

snitish commented Feb 8, 2025

take

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Constructors Series/DataFrame/Index/pd.array Constructors Dtype Conversions Unexpected or buggy dtype conversions
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants