Skip to content

REGR: to_datetime, unique with OOB values #31520

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

Merged
merged 1 commit into from
Feb 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions doc/source/whatsnew/v1.0.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ Categorical

Datetimelike
^^^^^^^^^^^^
-
-
- Fixed regression in :meth:`to_datetime` when parsing non-nanosecond resolution datetimes (:issue:`31491`)
- Fixed bug in :meth:`to_datetime` raising when ``cache=True`` and out-of-bound values are present (:issue:`31491`)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was present in 0.25.3, so technically not a regression.

Do we want to collect fixed regression in a dedicated section? I think we've done that in the past.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure would be a-ok


Timedelta
^^^^^^^^^
Expand Down
6 changes: 6 additions & 0 deletions pandas/core/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
is_categorical_dtype,
is_complex_dtype,
is_datetime64_any_dtype,
is_datetime64_dtype,
is_datetime64_ns_dtype,
is_extension_array_dtype,
is_float_dtype,
Expand Down Expand Up @@ -191,6 +192,11 @@ def _reconstruct_data(values, dtype, original):
if isinstance(original, ABCIndexClass):
values = values.astype(object, copy=False)
elif dtype is not None:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is period an issue here? (just comments, can target master)

if is_datetime64_dtype(dtype):
dtype = "datetime64[ns]"
elif is_timedelta64_dtype(dtype):
dtype = "timedelta64[ns]"

values = values.astype(dtype, copy=False)

return values
Expand Down
16 changes: 14 additions & 2 deletions pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,9 @@ def to_datetime(
cache : bool, default True
If True, use a cache of unique, converted dates to apply the datetime
conversion. May produce significant speed-up when parsing duplicate
date strings, especially ones with timezone offsets.
date strings, especially ones with timezone offsets. The cache is only
used when there are at least 50 values. The presence of out-of-bounds
values will render the cache unusable and may slow down parsing.

.. versionadded:: 0.23.0

Expand Down Expand Up @@ -734,7 +736,17 @@ def to_datetime(
convert_listlike = partial(convert_listlike, name=arg.name)
result = convert_listlike(arg, format)
elif is_list_like(arg):
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
try:
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
except tslibs.OutOfBoundsDatetime:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the best we can do here, at least without major surgery. It'll involve double-parsing the input for large arrays with errors='coerce'.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, pls create an issue as this should be handled directly in _maybe_cache itself

# caching attempts to create a DatetimeIndex, which may raise
# an OOB. If that's the desired behavior, then just reraise...
if errors == "raise":
raise
# ... otherwise, continue without the cache.
from pandas import Series

cache_array = Series([], dtype=object) # just an empty array
if not cache_array.empty:
result = _convert_and_box_cache(arg, cache_array)
else:
Expand Down
18 changes: 10 additions & 8 deletions pandas/tests/indexes/datetimes/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,9 +559,14 @@ def test_to_datetime_dt64s_out_of_bounds(self, cache, dt):
assert pd.to_datetime(dt, errors="coerce", cache=cache) is NaT

@pytest.mark.parametrize("cache", [True, False])
def test_to_datetime_array_of_dt64s(self, cache):
dts = [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")]

@pytest.mark.parametrize("unit", ["s", "D"])
def test_to_datetime_array_of_dt64s(self, cache, unit):
# https://github.com/pandas-dev/pandas/issues/31491
# Need at least 50 to ensure cache is used.
dts = [
np.datetime64("2000-01-01", unit),
np.datetime64("2000-01-02", unit),
] * 30
# Assuming all datetimes are in bounds, to_datetime() returns
# an array that is equal to Timestamp() parsing
tm.assert_index_equal(
Expand All @@ -579,11 +584,8 @@ def test_to_datetime_array_of_dt64s(self, cache):
tm.assert_index_equal(
pd.to_datetime(dts_with_oob, errors="coerce", cache=cache),
pd.DatetimeIndex(
[
Timestamp(dts_with_oob[0]).asm8,
Timestamp(dts_with_oob[1]).asm8,
pd.NaT,
]
[Timestamp(dts_with_oob[0]).asm8, Timestamp(dts_with_oob[1]).asm8] * 30
+ [pd.NaT],
),
)

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/test_algos.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,18 @@ def test_datetime64_dtype_array_returned(self):
tm.assert_numpy_array_equal(result, expected)
assert result.dtype == expected.dtype

def test_datetime_non_ns(self):
a = np.array(["2000", "2000", "2001"], dtype="datetime64[s]")
result = pd.unique(a)
expected = np.array(["2000", "2001"], dtype="datetime64[ns]")
tm.assert_numpy_array_equal(result, expected)

def test_timedelta_non_ns(self):
a = np.array(["2000", "2000", "2001"], dtype="timedelta64[s]")
result = pd.unique(a)
expected = np.array([2000000000000, 2001000000000], dtype="timedelta64[ns]")
tm.assert_numpy_array_equal(result, expected)

def test_timedelta64_dtype_array_returned(self):
# GH 9431
expected = np.array([31200, 45678, 10000], dtype="m8[ns]")
Expand Down