8000 REF: use shareable code for DTI/TDI.insert by jbrockmendel · Pull Request #30806 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

REF: use shareable code for DTI/TDI.insert #30806

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 6 commits into from
Jan 9, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
REF: use shareable code for DTI/TDI.insert
  • Loading branch information
jbrockmendel committed Jan 8, 2020
commit ff4044be1a2002fa0783a93397bca8816ff05f20
19 changes: 9 additions & 10 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,7 +922,9 @@ def insert(self, loc, item):
-------
new_index : Index
"""
if is_valid_nat_for_dtype(item, self.dtype):
if isinstance(item, self._data._recognized_scalars):
item = self._data._scalar_type(item)
elif is_valid_nat_for_dtype(item, self.dtype):
# GH 18295
item = self._na_value
elif is_scalar(item) and isna(item):
10000 Expand All @@ -932,11 +934,8 @@ def insert(self, loc, item):
)

freq = None

if isinstance(item, (datetime, np.datetime64)):
self._assert_can_do_op(item)
if not self._has_same_tz(item) and not isna(item):
raise ValueError("Passed item and index have different timezone")
if isinstance(item, self._data._scalar_type) or item is NaT:
self._data._check_compatible_with(item, setitem=True)

# check freq can be preserved on edge cases
if self.size and self.freq is not None:
Expand All @@ -946,19 +945,19 @@ def insert(self, loc, item):
freq = self.freq
elif (loc == len(self)) and item - self.freq == self[-1]:
freq = self.freq
item = _to_M8(item, tz=self.tz)
item = item.asm8

try:
new_dates = np.concatenate(
new_i8s = np.concatenate(
(self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8)
)
return self._shallow_copy(new_dates, freq=freq)
return self._shallow_copy(new_i8s, freq=freq)
except (AttributeError, TypeError):

# fall back to object index
if isinstance(item, str):
return self.astype(object).insert(loc, item)
raise TypeError("cannot insert DatetimeIndex with incompatible label")
raise TypeError(f"cannot insert {type(self).__name__} with incompatible label")

def indexer_at_time(self, time, asof=False):
"""
Expand Down
20 changes: 11 additions & 9 deletions pandas/core/indexes/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ def insert(self, loc, item):
"""
# try to convert if possible
if isinstance(item, self._data._recognized_scalars):
item = Timedelta(item)
item = self._data._scalar_type(item)
elif is_valid_nat_for_dtype(item, self.dtype):
# GH 18295
item = self._na_value
Expand All @@ -409,28 +409,30 @@ def insert(self, loc, item):
)

freq = None
if isinstance(item, Timedelta) or (is_scalar(item) and isna(item)):
if isinstance(item, self._data._scalar_type) or item is NaT:
self._data._check_compatible_with(item, setitem=True)

# check freq can be preserved on edge cases
if self.freq is not None:
if (loc == 0 or loc == -len(self)) and item + self.freq == self[0]:
if self.size and self.freq is not None:
if item is NaT:
pass
elif (loc == 0 or loc == -len(self)) and item + self.freq == self[0]:
freq = self.freq
elif (loc == len(self)) and item - self.freq == self[-1]:
freq = self.freq
item = Timedelta(item).asm8.view(_TD_DTYPE)
item = item.asm8

try:
new_tds = np.concatenate(
new_i8s = np.concatenate(
(self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8)
)
return self._shallow_copy(new_tds, freq=freq)

return self._shallow_copy(new_i8s, freq=freq)
except (AttributeError, TypeError):

# fall back to object index
if isinstance(item, str):
return self.astype(object).insert(loc, item)
raise TypeError("cannot insert TimedeltaIndex with incompatible label")
raise TypeError(f"cannot insert {type(self).__name__} with incompatible label")


TimedeltaIndex._add_comparison_ops()
Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/arithmetic/test_datetime64.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
date_range,
)
import pandas._testing as tm
from pandas.core.indexes.datetimes import _to_M8
from pandas.core.ops import roperator
from pandas.tests.arithmetic.common import (
assert_invalid_addsub_type,
Expand Down Expand Up @@ -341,7 +340,7 @@ class TestDatetimeIndexComparisons:
def test_comparators(self, op):
index = tm.makeDateIndex(100)
element = index[len(index) // 2]
element = _to_M8(element)
element = Timestamp(element).to_datetime64()

arr = np.array(index)
arr_result = op(arr, element)
Expand Down
0