Skip to content

BUG: TimedeltaIndex.searchsorted accepting invalid types/dtypes #30831

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
Jan 9, 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
22 changes: 18 additions & 4 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,11 +357,25 @@ def _partial_td_slice(self, key):
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, (np.ndarray, Index)):
value = np.array(value, dtype=_TD_DTYPE, copy=False)
else:
value = Timedelta(value).asm8.view(_TD_DTYPE)
if not type(self._data)._is_recognized_dtype(value):
raise TypeError(
"searchsorted requires compatible dtype or scalar, "
f"not {type(value).__name__}"
)
value = type(self._data)(value)
self._data._check_compatible_with(value)

elif isinstance(value, self._data._recognized_scalars):
self._data._check_compatible_with(value)
value = self._data._scalar_type(value)

elif not isinstance(value, TimedeltaArray):
raise TypeError(
"searchsorted requires compatible dtype or scalar, "
f"not {type(value).__name__}"
)

return self.values.searchsorted(value, side=side, sorter=sorter)
return self._data.searchsorted(value, side=side, sorter=sorter)

def is_type_compatible(self, typ) -> bool:
return typ == self.inferred_type or typ == "timedelta"
Expand Down
36 changes: 36 additions & 0 deletions pandas/tests/arrays/test_timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,42 @@ def test_setitem_objects(self, obj):
arr[0] = obj
assert arr[0] == pd.Timedelta(seconds=1)

@pytest.mark.parametrize(
"other",
[
1,
np.int64(1),
1.0,
np.datetime64("NaT"),
pd.Timestamp.now(),
"invalid",
np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9,
(np.arange(10) * 24 * 3600 * 10 ** 9).view("datetime64[ns]"),
pd.Timestamp.now().to_period("D"),
],
)
@pytest.mark.parametrize(
"index",
[
True,
pytest.param(
False,
marks=pytest.mark.xfail(
reason="Raises ValueError instead of TypeError", raises=ValueError
),
),
],
)
def test_searchsorted_invalid_types(self, other, index):
data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
arr = TimedeltaArray(data, freq="D")
if index:
arr = pd.Index(arr)

msg = "searchsorted requires compatible dtype or scalar"
with pytest.raises(TypeError, match=msg):
arr.searchsorted(other)


class TestReductions:
@pytest.mark.parametrize("name", ["sum", "std", "min", "max", "median"])
Expand Down