Skip to content

dispatch Series[datetime64] ops to DatetimeIndex #19024

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 7 commits into from
Jan 4, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,9 @@ Other API Changes
- In :func:`read_excel`, the ``comment`` argument is now exposed as a named parameter (:issue:`18735`)
- Rearranged the order of keyword arguments in :func:`read_excel()` to align with :func:`read_csv()` (:issue:`16672`)
- The options ``html.border`` and ``mode.use_inf_as_null`` were deprecated in prior versions, these will now show ``FutureWarning`` rather than a ``DeprecationWarning`` (:issue:`19003`)
- Subtracting ``NaT`` from a :class:`Series` with ``dtype='datetime64[ns]'`` returns a ``Series`` with ``dtype='timedelta64[ns]'`` instead of ``dtype='datetime64[ns]'``(:issue:`18808`)
- Operations between a :class:`Series` with dtype ``dtype='datetime64[ns]'`` and a :class:`PeriodIndex` will correctly raises ``TypeError`` (:issue:`18850`)
- Subtraction of :class:`Series` with timezone-aware ``dtype='datetime64[ns]'`` will mis-matched timezones will raise ``TypeError`` instead of ``ValueError`` (issue:`18817`) dtypewith mis-matched timezones will now raise a ``TypeError`` instead of a ``ValueError`` (:issue:`18817`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like some text got duped in the last entry


.. _whatsnew_0230.deprecations:

Expand Down
24 changes: 18 additions & 6 deletions pandas/core/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,13 @@ def wrapper(left, right, name=name, na_op=na_op):
return NotImplemented

left, right = _align_method_SERIES(left, right)
if is_datetime64_dtype(left) or is_datetime64tz_dtype(left):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and until / unless you want to limit / remove _TimeOp (which is actually ok with me). then this doesn't belong here as I have commented before.

You are welcome to put it in _TimeOp for now or rip out TimeOp.

result = op(pd.DatetimeIndex(left), right)
res_name = _get_series_op_result_name(left, right)
result.name = res_name # needs to be overriden if None
return construct_result(left, result,
index=left.index, name=res_name,
dtype=result.dtype)

converted = _Op.get_op(left, right, name, na_op)

Expand All @@ -754,31 +761,36 @@ 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)):
lvalues = lvalues.values

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

return wrapper


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


def _comp_method_OBJECT_ARRAY(op, x, y):
if isinstance(y, list):
y = construct_1d_object_array_from_listlike(y)
Expand Down
31 changes: 25 additions & 6 deletions pandas/tests/series/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,13 @@ def test_timedelta64_ops_nat(self):
assert_series_equal(timedelta_series / nan,
nat_series_dtype_timedelta)

def test_td64_sub_NaT(self):
# GH#18808
ser = Series([NaT, Timedelta('1s')])
res = ser - NaT
expected = Series([NaT, NaT], dtype='timedelta64[ns]')
tm.assert_series_equal(res, expected)

@pytest.mark.parametrize('scalar_td', [timedelta(minutes=5, seconds=4),
Timedelta(minutes=5, seconds=4),
Timedelta('5m4s').to_timedelta64()])
Expand Down Expand Up @@ -1076,7 +1083,7 @@ def run_ops(ops, get_ser, test_ser):
# defined
for op_str in ops:
op = getattr(get_ser, op_str, None)
with tm.assert_raises_regex(TypeError, 'operate'):
with tm.assert_raises_regex(TypeError, 'operate|cannot'):
op(test_ser)

# ## timedelta64 ###
Expand Down Expand Up @@ -1253,20 +1260,31 @@ def test_datetime_series_with_DateOffset(self):
s + op(5)
op(5) + s

def test_dt64_sub_NaT(self):
# GH#18808
dti = pd.DatetimeIndex([pd.NaT, pd.Timestamp('19900315')])
ser = pd.Series(dti)
res = ser - pd.NaT
expected = pd.Series([pd.NaT, pd.NaT], dtype='timedelta64[ns]')
tm.assert_series_equal(res, expected)

dti_tz = dti.tz_localize('Asia/Tokyo')
ser_tz = pd.Series(dti_tz)
res = ser_tz - pd.NaT
expected = pd.Series([pd.NaT, pd.NaT], dtype='timedelta64[ns]')
tm.assert_series_equal(res, expected)

def test_datetime64_ops_nat(self):
# GH 11349
datetime_series = Series([NaT, Timestamp('19900315')])
nat_series_dtype_timestamp = Series([NaT, NaT], dtype='datetime64[ns]')
single_nat_dtype_datetime = Series([NaT], dtype='datetime64[ns]')

# subtraction
assert_series_equal(datetime_series - NaT, nat_series_dtype_timestamp)
assert_series_equal(-NaT + datetime_series, nat_series_dtype_timestamp)
with pytest.raises(TypeError):
-single_nat_dtype_datetime + datetime_series

assert_series_equal(nat_series_dtype_timestamp - NaT,
nat_series_dtype_timestamp)
assert_series_equal(-NaT + nat_series_dtype_timestamp,
nat_series_dtype_timestamp)
with pytest.raises(TypeError):
Expand Down Expand Up @@ -2036,8 +2054,9 @@ def test_datetime64_with_index(self):
result = s - s.index
assert_series_equal(result, expected)

result = s - s.index.to_period()
assert_series_equal(result, expected)
with pytest.raises(TypeError):
# GH#18850
result = s - s.index.to_period()

df = DataFrame(np.random.randn(5, 2),
index=date_range('20130101', periods=5))
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/series/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def test_shift(self):
# incompat tz
s2 = Series(date_range('2000-01-01 09:00:00', periods=5,
tz='CET'), name='foo')
pytest.raises(ValueError, lambda: s - s2)
pytest.raises(TypeError, lambda: s - s2)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this in the whatsnew notes API changed section?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes


def test_shift2(self):
ts = Series(np.random.randn(5),
Expand Down