Skip to content

BUG: DataFrame[int] +/- datetime64 #28362

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 14 commits into from
Sep 12, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ Datetimelike
- Bug in :meth:`pandas.core.groupby.SeriesGroupBy.nunique` where ``NaT`` values were interfering with the count of unique values (:issue:`27951`)
- Bug in :class:`Timestamp` subtraction when subtracting a :class:`Timestamp` from a ``np.datetime64`` object incorrectly raising ``TypeError`` (:issue:`28286`)
- Addition and subtraction of integer or integer-dtype arrays with :class:`Timestamp` will now raise ``NullFrequencyError`` instead of ``ValueError`` (:issue:`28268`)
- Bug in :class:`Series` and :class:`DataFrame` with integer dtype failing to raise ``TypeError`` when adding or subtracting a ``np.datetime64`` object (:issue:`28080`)
-


Timedelta
Expand Down
6 changes: 6 additions & 0 deletions pandas/_libs/tslibs/nattype.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,8 @@ cdef class _NaT(datetime):
result = np.empty(other.shape, dtype="datetime64[ns]")
result.fill("NaT")
return result
raise TypeError("Cannot add NaT to ndarray with dtype {dtype}"
.format(dtype=other.dtype))

return NotImplemented

Expand Down Expand Up @@ -201,6 +203,10 @@ cdef class _NaT(datetime):
result.fill("NaT")
return result

raise TypeError(
"Cannot subtract NaT from ndarray with dtype {dtype}"
.format(dtype=other.dtype))

return NotImplemented

def __pos__(self):
Expand Down
33 changes: 23 additions & 10 deletions pandas/core/ops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import numpy as np

from pandas._libs import Timedelta, lib, ops as libops
from pandas._libs import Timedelta, Timestamp, lib, ops as libops
from pandas.errors import NullFrequencyError
from pandas.util._decorators import Appender

Expand Down Expand Up @@ -148,13 +148,24 @@ def maybe_upcast_for_op(obj, shape: Tuple[int, ...]):
Be careful to call this *after* determining the `name` attribute to be
attached to the result of the arithmetic operation.
"""
from pandas.core.arrays import TimedeltaArray
from pandas.core.arrays import DatetimeArray, TimedeltaArray

if type(obj) is datetime.timedelta:
# GH#22390 cast up to Timedelta to rely on Timedelta
# implementation; otherwise operation against numeric-dtype
# raises TypeError
return Timedelta(obj)
elif isinstance(obj, np.datetime64):
# GH#28080 numpy casts integer-dtype to datetime64 when doing
# array[int] + datetime64, which we do not allow
if isna(obj):
# Avoid possible ambiguities with pd.NaT
obj = obj.astype("datetime64[ns]")
right = np.broadcast_to(obj, shape)
return DatetimeArray(right)

return Timestamp(obj)

elif isinstance(obj, np.timedelta64):
if isna(obj):
# wrapping timedelta64("NaT") in Timedelta returns NaT,
Expand Down Expand Up @@ -624,7 +635,13 @@ def wrapper(left, right):

keep_null_freq = isinstance(
right,
(ABCDatetimeIndex, ABCDatetimeArray, ABCTimedeltaIndex, ABCTimedeltaArray),
(
ABCDatetimeIndex,
ABCDatetimeArray,
ABCTimedeltaIndex,
ABCTimedeltaArray,
Timestamp,
),
)

left, right = _align_method_SERIES(left, right)
Expand All @@ -635,13 +652,9 @@ def wrapper(left, right):

rvalues = maybe_upcast_for_op(rvalues, lvalues.shape)

if should_extension_dispatch(lvalues, rvalues):
result = dispatch_to_extension_op(op, lvalues, rvalues, keep_null_freq)

elif is_timedelta64_dtype(rvalues) or isinstance(rvalues, ABCDatetimeArray):
# We should only get here with td64 rvalues with non-scalar values
# for rvalues upcast by maybe_upcast_for_op
assert not isinstance(rvalues, (np.timedelta64, np.ndarray))
if should_extension_dispatch(left, rvalues) or isinstance(
rvalues, (ABCTimedeltaArray, ABCDatetimeArray, Timestamp)
):
result = dispatch_to_extension_op(op, lvalues, rvalues, keep_null_freq)

else:
Expand Down
28 changes: 26 additions & 2 deletions pandas/tests/arithmetic/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ def test_compare_invalid(self):


# ------------------------------------------------------------------
# Numeric dtypes Arithmetic with Timedelta Scalar
# Numeric dtypes Arithmetic with Datetime/Timedelta Scalar


class TestNumericArraylikeArithmeticWithTimedeltaLike:
class TestNumericArraylikeArithmeticWithDatetimeLike:

# TODO: also check name retentention
@pytest.mark.parametrize("box_cls", [np.array, pd.Index, pd.Series])
Expand Down Expand Up @@ -235,6 +235,30 @@ def test_add_sub_timedeltalike_invalid(self, numeric_idx, other, box):
with pytest.raises(TypeError):
other - left

@pytest.mark.parametrize(
"other",
[
pd.Timestamp.now().to_pydatetime(),
pd.Timestamp.now(tz="UTC").to_pydatetime(),
pd.Timestamp.now().to_datetime64(),
pd.NaT,
],
)
@pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning")
def test_add_sub_datetimelike_invalid(self, numeric_idx, other, box):
# GH#28080 numeric+datetime64 should raise; Timestamp raises
# NullFrequencyError instead of TypeError so is excluded.
left = tm.box_expected(numeric_idx, box)

with pytest.raises(TypeError):
left + other
with pytest.raises(TypeError):
other + left
with pytest.raises(TypeError):
left - other
with pytest.raises(TypeError):
other - left


# ------------------------------------------------------------------
# Arithmetic
Expand Down