Skip to content

Commit

Permalink
Fix Series[timedelta64]+DatetimeIndex[tz] bugs (pandas-dev#18884)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored and jreback committed Jan 2, 2018
1 parent a697421 commit 04beec7
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 12 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ Numeric

- Bug in :func:`Series.__sub__` subtracting a non-nanosecond ``np.datetime64`` object from a ``Series`` gave incorrect results (:issue:`7996`)
- Bug in :class:`DatetimeIndex`, :class:`TimedeltaIndex` addition and subtraction of zero-dimensional integer arrays gave incorrect results (:issue:`19012`)
- Bug in :func:`Series.__add__` adding Series with dtype ``timedelta64[ns]`` to a timezone-aware ``DatetimeIndex`` incorrectly dropped timezone information (:issue:`13905`)
-

Categorical
Expand Down
8 changes: 6 additions & 2 deletions pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,9 @@ def __add__(self, other):
from pandas.tseries.offsets import DateOffset

other = lib.item_from_zerodim(other)
if is_timedelta64_dtype(other):
if isinstance(other, ABCSeries):
return NotImplemented
elif is_timedelta64_dtype(other):
return self._add_delta(other)
elif isinstance(self, TimedeltaIndex) and isinstance(other, Index):
if hasattr(other, '_add_delta'):
Expand Down Expand Up @@ -702,7 +704,9 @@ def __sub__(self, other):
from pandas.tseries.offsets import DateOffset

other = lib.item_from_zerodim(other)
if is_timedelta64_dtype(other):
if isinstance(other, ABCSeries):
return NotImplemented
elif is_timedelta64_dtype(other):
return self._add_delta(-other)
elif isinstance(self, TimedeltaIndex) and isinstance(other, Index):
if not isinstance(other, TimedeltaIndex):
Expand Down
3 changes: 3 additions & 0 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,9 @@ def _maybe_update_attributes(self, attrs):
return attrs

def _add_delta(self, delta):
if isinstance(delta, ABCSeries):
return NotImplemented

from pandas import TimedeltaIndex
name = self.name

Expand Down
27 changes: 17 additions & 10 deletions pandas/core/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
from pandas.core.dtypes.generic import (
ABCSeries,
ABCDataFrame,
ABCIndex,
ABCIndex, ABCDatetimeIndex,
ABCPeriodIndex)

# -----------------------------------------------------------------------------
Expand Down Expand Up @@ -514,8 +514,9 @@ def _convert_to_array(self, values, name=None, other=None):
values[:] = iNaT

# a datelike
elif isinstance(values, pd.DatetimeIndex):
values = values.to_series()
elif isinstance(values, ABCDatetimeIndex):
# TODO: why are we casting to_series in the first place?
values = values.to_series(keep_tz=True)
# datetime with tz
elif (isinstance(ovalues, datetime.datetime) and
hasattr(ovalues, 'tzinfo')):
Expand All @@ -535,6 +536,11 @@ def _convert_to_array(self, values, name=None, other=None):
elif inferred_type in ('timedelta', 'timedelta64'):
# have a timedelta, convert to to ns here
values = to_timedelta(values, errors='coerce', box=False)
if isinstance(other, ABCDatetimeIndex):
# GH#13905
# Defer to DatetimeIndex/TimedeltaIndex operations where
# timezones are handled carefully.
values = pd.TimedeltaIndex(values)
elif inferred_type == 'integer':
# py3 compat where dtype is 'm' but is an integer
if values.dtype.kind == 'm':
Expand Down Expand Up @@ -754,25 +760,26 @@ def wrapper(left, right, name=name, na_op=na_op):
na_op = converted.na_op

if isinstance(rvalues, ABCSeries):
name = _maybe_match_name(left, rvalues)
lvalues = getattr(lvalues, 'values', lvalues)
rvalues = getattr(rvalues, 'values', rvalues)
# _Op aligns left and right
else:
if isinstance(rvalues, pd.Index):
name = _maybe_match_name(left, rvalues)
else:
name = left.name
if (hasattr(lvalues, 'values') and
not isinstance(lvalues, pd.DatetimeIndex)):
not isinstance(lvalues, ABCDatetimeIndex)):
lvalues = lvalues.values

if isinstance(right, (ABCSeries, pd.Index)):
# `left` is always a Series object
res_name = _maybe_match_name(left, right)
else:
res_name = left.name

result = wrap_results(safe_na_op(lvalues, rvalues))
return construct_result(
left,
result,
index=left.index,
name=name,
name=res_name,
dtype=dtype,
)

Expand Down
27 changes: 27 additions & 0 deletions pandas/tests/indexes/datetimes/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,33 @@ def test_datetimeindex_sub_timestamp_overflow(self):
with pytest.raises(OverflowError):
dtimin - variant

@pytest.mark.parametrize('names', [('foo', None, None),
('baz', 'bar', None),
('bar', 'bar', 'bar')])
@pytest.mark.parametrize('tz', [None, 'America/Chicago'])
def test_dti_add_series(self, tz, names):
# GH#13905
index = DatetimeIndex(['2016-06-28 05:30', '2016-06-28 05:31'],
tz=tz, name=names[0])
ser = Series([Timedelta(seconds=5)] * 2,
index=index, name=names[1])
expected = Series(index + Timedelta(seconds=5),
index=index, name=names[2])

# passing name arg isn't enough when names[2] is None
expected.name = names[2]
assert expected.dtype == index.dtype
result = ser + index
tm.assert_series_equal(result, expected)
result2 = index + ser
tm.assert_series_equal(result2, expected)

expected = index + Timedelta(seconds=5)
result3 = ser.values + index
tm.assert_index_equal(result3, expected)
result4 = index + ser.values
tm.assert_index_equal(result4, expected)

@pytest.mark.parametrize('box', [np.array, pd.Index])
def test_dti_add_offset_array(self, tz, box):
# GH#18849
Expand Down

0 comments on commit 04beec7

Please sign in to comment.