Description
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 numpy as np
import pandas as pd
pdf = pd.DataFrame([1., 2., np.nan])
# The next line triggers a RuntimeWarning
pd.to_timedelta(pdf[0], unit='s')
Issue Description
The following change in numpy>1.24 is triggering a RuntimeWarning
when trying to convert a np.nan
to a pandas datetime object.
The cause of the problem (numpy change) is similar to #50681, but the fix on the pandas side is distinct. Hence this new issue.
Expected Behavior
No warning should be issued. I believe this could be fixed by not using .astype(np.int64)
, but rather .round(0)
in the relevant part of the code (l.902-916 in core/arrays/timedeltas.py). Unless this would lead to precision issues, as warned in the comments ?
Edit: The .view()
command leads to floating point errors at times (with my new proposition of code). Using .astype()
seems to work better ... but some more thoughts is likely required to find a solid solution.
elif is_float_dtype(data.dtype):
# cast the unit, multiply base/frac separately
# to avoid precision issues from float -> int
mask = np.isnan(data)
# The next few lines are effectively a vectorized 'cast_from_unit'
m, p = precision_from_unit(unit or "ns")
#base = data.astype(np.int64) # original
base = data.round(0) # My suggestion
frac = data - base
if p:
frac = np.round(frac, p)
#data = (base * m + (frac * m).astype(np.int64)).view("timedelta64[ns]") # original
data = (base * m + (frac * m).round(0)).astype("timedelta64[ns]") # My suggestion
data[mask] = iNaT
copy = False
Installed Versions
INSTALLED VERSIONS
commit : 8dab54d
python : 3.10.6.final.0
python-bits : 64
OS : Darwin
OS-release : 22.1.0
Version : Darwin Kernel Version 22.1.0: Sun Oct 9 20:14:54 PDT 2022; root:xnu-8792.41.9~2/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8
pandas : 1.5.2
numpy : 1.24.1
pytz : 2022.7
dateutil : 2.8.2
setuptools : 65.6.3
pip : 22.3.1
Cython : None
pytest : 7.2.0
hypothesis : None
sphinx : 5.3.0
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.6.0
pandas_datareader: None
bs4 : None
bottleneck : None
brotli :
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.1
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.9.3
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None
tzdata : None