Skip to content

Commit 4b91140

Browse files
jbrockmendeljreback
authored andcommitted
DTA Followups - remove redundant methods (#24577)
1 parent 9ad1e00 commit 4b91140

File tree

11 files changed

+110
-214
lines changed

11 files changed

+110
-214
lines changed

pandas/core/arrays/datetimelike.py

+5-70
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,11 @@
1919
from pandas.util._validators import validate_fillna_kwargs
2020

2121
from pandas.core.dtypes.common import (
22-
is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype,
23-
is_datetime64_dtype, is_datetime64tz_dtype, is_datetime_or_timedelta_dtype,
24-
is_dtype_equal, is_extension_array_dtype, is_float_dtype, is_integer_dtype,
25-
is_list_like, is_object_dtype, is_offsetlike, is_period_dtype,
26-
is_string_dtype, is_timedelta64_dtype, is_unsigned_integer_dtype,
27-
needs_i8_conversion, pandas_dtype)
22+
is_categorical_dtype, is_datetime64_any_dtype, is_datetime64_dtype,
23+
is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_dtype_equal,
24+
is_extension_array_dtype, is_float_dtype, is_integer_dtype, is_list_like,
25+
is_object_dtype, is_offsetlike, is_period_dtype, is_string_dtype,
26+
is_timedelta64_dtype, is_unsigned_integer_dtype, pandas_dtype)
2827
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
2928
from pandas.core.dtypes.inference import is_array_like
3029
from pandas.core.dtypes.missing import isna
@@ -40,32 +39,6 @@
4039
from .base import ExtensionArray, ExtensionOpsMixin
4140

4241

43-
def _make_comparison_op(cls, op):
44-
# TODO: share code with indexes.base version? Main difference is that
45-
# the block for MultiIndex was removed here.
46-
def cmp_method(self, other):
47-
if isinstance(other, ABCDataFrame):
48-
return NotImplemented
49-
50-
if needs_i8_conversion(self) and needs_i8_conversion(other):
51-
# we may need to directly compare underlying
52-
# representations
53-
return self._evaluate_compare(other, op)
54-
55-
# numpy will show a DeprecationWarning on invalid elementwise
56-
# comparisons, this will raise in the future
57-
with warnings.catch_warnings(record=True):
58-
warnings.filterwarnings("ignore", "elementwise", FutureWarning)
59-
with np.errstate(all='ignore'):
60-
result = op(self._data, np.asarray(other))
61-
62-
return result
63-
64-
name = '__{name}__'.format(name=op.__name__)
65-
# TODO: docstring?
66-
return compat.set_function_name(cmp_method, name, cls)
67-
68-
6942
class AttributesMixin(object):
7043

7144
@property
@@ -1358,41 +1331,6 @@ def __isub__(self, other):
13581331
# --------------------------------------------------------------
13591332
# Comparison Methods
13601333

1361-
# Called by _add_comparison_methods defined in ExtensionOpsMixin
1362-
_create_comparison_method = classmethod(_make_comparison_op)
1363-
1364-
def _evaluate_compare(self, other, op):
1365-
"""
1366-
We have been called because a comparison between
1367-
8 aware arrays. numpy will warn about NaT comparisons
1368-
"""
1369-
# Called by comparison methods when comparing datetimelike
1370-
# with datetimelike
1371-
1372-
if not isinstance(other, type(self)):
1373-
# coerce to a similar object
1374-
if not is_list_like(other):
1375-
# scalar
1376-
other = [other]
1377-
elif lib.is_scalar(lib.item_from_zerodim(other)):
1378-
# ndarray scalar
1379-
other = [other.item()]
1380-
other = type(self)._from_sequence(other)
1381-
1382-
# compare
1383-
result = op(self.asi8, other.asi8)
1384-
1385-
# technically we could support bool dtyped Index
1386-
# for now just return the indexing array directly
1387-
mask = (self._isnan) | (other._isnan)
1388-
1389-
filler = iNaT
1390-
if is_bool_dtype(result):
1391-
filler = False
1392-
1393-
result[mask] = filler
1394-
return result
1395-
13961334
def _ensure_localized(self, arg, ambiguous='raise', nonexistent='raise',
13971335
from_utc=False):
13981336
"""
@@ -1493,9 +1431,6 @@ def max(self, axis=None, skipna=True, *args, **kwargs):
14931431
return self._box_func(result)
14941432

14951433

1496-
DatetimeLikeArrayMixin._add_comparison_ops()
1497-
1498-
14991434
# -------------------------------------------------------------------
15001435
# Shared Constructor Helpers
15011436

pandas/core/arrays/datetimes.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
_midnight = time(0, 0)
3535

3636

37-
def _to_m8(key, tz=None):
37+
def _to_M8(key, tz=None):
3838
"""
3939
Timestamp-like => dt64
4040
"""
@@ -96,7 +96,6 @@ def _dt_array_cmp(cls, op):
9696
nat_result = True if opname == '__ne__' else False
9797

9898
def wrapper(self, other):
99-
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
10099
# TODO: return NotImplemented for Series / Index and let pandas unbox
101100
# Right now, returning NotImplemented for Index fails because we
102101
# go into the index implementation, which may be a bug?
@@ -109,7 +108,7 @@ def wrapper(self, other):
109108
self._assert_tzawareness_compat(other)
110109

111110
try:
112-
other = _to_m8(other, tz=self.tz)
111+
other = _to_M8(other, tz=self.tz)
113112
except ValueError:
114113
# string that cannot be parsed to Timestamp
115114
return ops.invalid_comparison(self, other, op)
@@ -158,7 +157,7 @@ def wrapper(self, other):
158157
# or an object-dtype ndarray
159158
other = type(self)._from_sequence(other)
160159

161-
result = meth(self, other)
160+
result = op(self.view('i8'), other.view('i8'))
162161
o_mask = other._isnan
163162

164163
result = com.values_from_object(result)

pandas/core/arrays/timedeltas.py

+3-17
Original file line numberDiff line numberDiff line change
@@ -36,18 +36,6 @@
3636
_BAD_DTYPE = "dtype {dtype} cannot be converted to timedelta64[ns]"
3737

3838

39-
def _to_m8(key):
40-
"""
41-
Timedelta-like => dt64
42-
"""
43-
if not isinstance(key, Timedelta):
44-
# this also converts strings
45-
key = Timedelta(key)
46-
47-
# return an type that can be compared
48-
return np.int64(key.value).view(_TD_DTYPE)
49-
50-
5139
def _is_convertible_to_td(key):
5240
return isinstance(key, (Tick, timedelta,
5341
np.timedelta64, compat.string_types))
@@ -75,17 +63,15 @@ def _td_array_cmp(cls, op):
7563
opname = '__{name}__'.format(name=op.__name__)
7664
nat_result = True if opname == '__ne__' else False
7765

78-
meth = getattr(dtl.DatetimeLikeArrayMixin, opname)
79-
8066
def wrapper(self, other):
8167
if _is_convertible_to_td(other) or other is NaT:
8268
try:
83-
other = _to_m8(other)
69+
other = Timedelta(other)
8470
except ValueError:
8571
# failed to parse as timedelta
8672
return ops.invalid_comparison(self, other, op)
8773

88-
result = meth(self, other)
74+
result = op(self.view('i8'), other.value)
8975
if isna(other):
9076
result.fill(nat_result)
9177

@@ -101,7 +87,7 @@ def wrapper(self, other):
10187
except (ValueError, TypeError):
10288
return ops.invalid_comparison(self, other, op)
10389

104-
result = meth(self, other)
90+
result = op(self.view('i8'), other.view('i8'))
10591
result = com.values_from_object(result)
10692

10793
o_mask = np.array(isna(other))

pandas/core/indexes/datetimelike.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg
1414

1515
from pandas.core.dtypes.common import (
16-
ensure_int64, is_bool_dtype, is_dtype_equal, is_float, is_integer,
17-
is_list_like, is_period_dtype, is_scalar)
16+
ensure_int64, is_dtype_equal, is_float, is_integer, is_list_like,
17+
is_period_dtype, is_scalar)
1818
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries
1919

2020
from pandas.core import algorithms, ops
@@ -191,16 +191,6 @@ def wrapper(left, right):
191191

192192
return wrapper
193193

194-
@Appender(DatetimeLikeArrayMixin._evaluate_compare.__doc__)
195-
def _evaluate_compare(self, other, op):
196-
result = self._eadata._evaluate_compare(other, op)
197-
if is_bool_dtype(result):
198-
return result
199-
try:
200-
return Index(result)
201-
except TypeError:
202-
return result
203-
204194
def _ensure_localized(self, arg, ambiguous='raise', nonexistent='raise',
205195
from_utc=False):
206196
# See DatetimeLikeArrayMixin._ensure_localized.__doc__

pandas/core/indexes/datetimes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
from pandas.core.accessor import delegate_names
2424
from pandas.core.arrays.datetimes import (
25-
DatetimeArrayMixin as DatetimeArray, _to_m8, validate_tz_from_dtype)
25+
DatetimeArrayMixin as DatetimeArray, _to_M8, validate_tz_from_dtype)
2626
from pandas.core.base import _shared_docs
2727
import pandas.core.common as com
2828
from pandas.core.indexes.base import Index
@@ -405,7 +405,7 @@ def __setstate__(self, state):
405405
def _convert_for_op(self, value):
406406
""" Convert value to be insertable to ndarray """
407407
if self._has_same_tz(value):
408-
return _to_m8(value)
408+
return _to_M8(value)
409409
raise ValueError('Passed item and index have different timezone')
410410

411411
def _maybe_update_attributes(self, attrs):
@@ -1161,7 +1161,7 @@ def searchsorted(self, value, side='left', sorter=None):
11611161
if isinstance(value, (np.ndarray, Index)):
11621162
value = np.array(value, dtype=_NS_DTYPE, copy=False)
11631163
else:
1164-
value = _to_m8(value, tz=self.tz)
1164+
value = _to_M8(value, tz=self.tz)
11651165

11661166
return self.values.searchsorted(value, side=side)
11671167

@@ -1211,7 +1211,7 @@ def insert(self, loc, item):
12111211
freq = self.freq
12121212
elif (loc == len(self)) and item - self.freq == self[-1]:
12131213
freq = self.freq
1214-
item = _to_m8(item, tz=self.tz)
1214+
item = _to_M8(item, tz=self.tz)
12151215

12161216
try:
12171217
new_dates = np.concatenate((self[:loc].asi8, [item.view(np.int64)],

pandas/core/indexes/period.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -276,9 +276,6 @@ def _simple_new(cls, values, name=None, freq=None, **kwargs):
276276
result._reset_identity()
277277
return result
278278

279-
# ------------------------------------------------------------------------
280-
# Wrapping PeriodArray
281-
282279
# ------------------------------------------------------------------------
283280
# Data
284281

@@ -416,6 +413,10 @@ def _mpl_repr(self):
416413
# how to represent ourselves to matplotlib
417414
return self.astype(object).values
418415

416+
@property
417+
def _formatter_func(self):
418+
return self.array._formatter(boxed=False)
419+
419420
# ------------------------------------------------------------------------
420421
# Indexing
421422

@@ -496,10 +497,6 @@ def __array_wrap__(self, result, context=None):
496497
# cannot pass _simple_new as it is
497498
return type(self)(result, freq=self.freq, name=self.name)
498499

499-
@property
500-
def _formatter_func(self):
501-
return self.array._formatter(boxed=False)
502-
503500
def asof_locs(self, where, mask):
504501
"""
505502
where : array of timestamps

pandas/core/indexes/timedeltas.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from pandas.core.accessor import delegate_names
1919
from pandas.core.arrays import datetimelike as dtl
2020
from pandas.core.arrays.timedeltas import (
21-
TimedeltaArrayMixin as TimedeltaArray, _is_convertible_to_td, _to_m8)
21+
TimedeltaArrayMixin as TimedeltaArray, _is_convertible_to_td)
2222
from pandas.core.base import _shared_docs
2323
import pandas.core.common as com
2424
from pandas.core.indexes.base import Index, _index_shared_docs
@@ -614,7 +614,7 @@ def searchsorted(self, value, side='left', sorter=None):
614614
if isinstance(value, (np.ndarray, Index)):
615615
value = np.array(value, dtype=_TD_DTYPE, copy=False)
616616
else:
617-
value = _to_m8(value)
617+
value = Timedelta(value).asm8.view(_TD_DTYPE)
618618

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

@@ -664,7 +664,7 @@ def insert(self, loc, item):
664664
freq = self.freq
665665
elif (loc == len(self)) and item - self.freq == self[-1]:
666666
freq = self.freq
667-
item = _to_m8(item)
667+
item = Timedelta(item).asm8.view(_TD_DTYPE)
668668

669669
try:
670670
new_tds = np.concatenate((self[:loc].asi8, [item.view(np.int64)],

pandas/tests/arithmetic/test_datetime64.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from pandas._libs.tslibs.conversion import localize_pydatetime
2121
from pandas._libs.tslibs.offsets import shift_months
2222

23-
from pandas.core.indexes.datetimes import _to_m8
23+
from pandas.core.indexes.datetimes import _to_M8
2424

2525
from pandas import (
2626
Timestamp, Timedelta, Period, Series, date_range, NaT,
@@ -349,7 +349,7 @@ class TestDatetimeIndexComparisons(object):
349349
def test_comparators(self, op):
350350
index = tm.makeDateIndex(100)
351351
element = index[len(index) // 2]
352-
element = _to_m8(element)
352+
element = _to_M8(element)
353353

354354
arr = np.array(index)
355355
arr_result = op(arr, element)

0 commit comments

Comments
 (0)