Skip to content

BUG/API: tighter checks on DTI/TDI.equals #36962

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 4 commits into from
Oct 8, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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: 4 additions & 0 deletions pandas/core/arrays/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from pandas.core.dtypes.common import (
DT64NS_DTYPE,
TD64NS_DTYPE,
is_categorical_dtype,
is_dtype_equal,
is_float_dtype,
is_integer_dtype,
Expand Down Expand Up @@ -940,6 +941,9 @@ def sequence_to_td64ns(data, copy=False, unit=None, errors="raise"):
data = data._data
elif isinstance(data, IntegerArray):
data = data.to_numpy("int64", na_value=tslibs.iNaT)
elif is_categorical_dtype(data.dtype):
data = data.categories.take(data.codes, fill_value=NaT)._values
copy = False

# Convert whatever we have into timedelta64[ns] dtype
if is_object_dtype(data.dtype) or is_string_dtype(data.dtype):
Expand Down
33 changes: 25 additions & 8 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from pandas.core.dtypes.common import (
ensure_int64,
is_bool_dtype,
is_categorical_dtype,
is_dtype_equal,
is_integer,
is_list_like,
Expand Down Expand Up @@ -137,14 +138,30 @@ def equals(self, other: object) -> bool:
elif other.dtype.kind in ["f", "i", "u", "c"]:
return False
elif not isinstance(other, type(self)):
try:
other = type(self)(other)
except (ValueError, TypeError, OverflowError):
# e.g.
# ValueError -> cannot parse str entry, or OutOfBoundsDatetime
# TypeError -> trying to convert IntervalIndex to DatetimeIndex
# OverflowError -> Index([very_large_timedeltas])
return False
inferrable = [
"timedelta",
"timedelta64",
"datetime",
"datetime64",
"date",
"period",
]

should_try = False
if other.dtype == object:
should_try = other.inferred_type in inferrable
elif is_categorical_dtype(other.dtype):
should_try = other.categories.inferred_type in inferrable

if should_try:
try:
other = type(self)(other)
except (ValueError, TypeError, OverflowError):
# e.g.
# ValueError -> cannot parse str entry, or OutOfBoundsDatetime
# TypeError -> trying to convert IntervalIndex to DatetimeIndex
# OverflowError -> Index([very_large_timedeltas])
return False

if not is_dtype_equal(self.dtype, other.dtype):
# have different timezone
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,20 @@ def test_not_equals_numeric(self):
assert not index.equals(pd.Index(index.asi8.astype("u8")))
assert not index.equals(pd.Index(index.asi8).astype("f8"))

def test_equals(self):
index = self.create_index()

assert index.equals(index.astype(object))
assert index.equals(pd.CategoricalIndex(index))
assert index.equals(pd.CategoricalIndex(index.astype(object)))

def test_not_equals_strings(self):
index = self.create_index()

other = pd.Index([str(x) for x in index], dtype=object)
assert not index.equals(other)
assert not index.equals(pd.CategoricalIndex(other))

def test_where_cast_str(self):
index = self.create_index()

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/indexes/timedeltas/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,15 @@ def test_explicit_none_freq(self):

result = TimedeltaIndex(tdi._data, freq=None)
assert result.freq is None

def test_from_categorical(self):
tdi = timedelta_range(1, periods=5)

cat = pd.Categorical(tdi)

result = TimedeltaIndex(cat)
tm.assert_index_equal(result, tdi)

ci = pd.CategoricalIndex(tdi)
result = TimedeltaIndex(ci)
tm.assert_index_equal(result, tdi)