8000 Fix arithmetic errors with timedelta64 dtypes by jbrockmendel · Pull Request #22390 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

Fix arithmetic errors with timedelta64 dtypes #22390

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
Aug 23, 2018
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
Prev Previous commit
Next Next commit
add GH references
  • Loading branch information
jbrockmendel committed Aug 16, 2018
commit c493b237709c995c6e17cd7fd0bd6d102321f624
8 changes: 4 additions & 4 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -576,10 +576,10 @@ Datetimelike
- Bug in :class:`DataFrame` with mixed dtypes including ``datetime64[ns]`` incorrectly raising ``TypeError`` on equality comparisons (:issue:`13128`,:issue:`22163`)
- Bug in :meth:`DataFrame.eq` comparison against ``NaT`` incorrectly returning ``True`` or ``NaN`` (:issue:`15697`,:issue:`22163`)
- Bug in :class:`DataFrame` with ``timedelta64[ns]`` dtype division by ``Timedelta``-like scalar incorrectly returning ``timedelta64[ns]`` dtype instead of ``float64`` dtype (:issue:`20088`,:issue:`22163`)
Copy link
Contributor

Choose a reason for hiding this comment

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

can you split out to a timedelta bug section (as this is getting kind of long)?

can be in a future PR

Copy link
Member Author

Choose a reason for hiding this comment

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

Sounds good

Copy link
Contributor

Choose a reason for hiding this comment

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

I think we now have a separate section?

- Bug in adding a :class:`Index` with object dtype to a :class:`Series` with ``timedelta64[ns]`` dtype incorrectly raising (:issue:`?????`)
- Bug in multiplying a :class:`Series` with numeric dtype against a ``timedelta`` object (:issue:`?????`)
- Bug in :class:`Series` with numeric dtype when adding or subtracting an an array or ``Series`` with ``timedelta64`` dtype (:issue:`?????`)
- Bug in :class:`Index` with numeric dtype when multiplying or dividing an array with dtype ``timedelta64`` (:issue:`????`)
- Bug in adding a :class:`Index` with object dtype to a :class:`Series` with ``timedelta64[ns]`` dtype incorrectly raising (:issue:`22390`)
- Bug in multiplying a :class:`Series` with numeric dtype against a ``timedelta`` object (:issue:`22390`)
- Bug in :class:`Series` with numeric dtype when adding or subtracting an an array or ``Series`` with ``timedelta64`` dtype (:issue:`22390`)
- Bug in :class:`Index` with numeric dtype when multiplying or dividing an array with dtype ``timedelta64`` (:issue:`22390`)

Timedelta
^^^^^^^^^
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ def index_arithmetic_method(self, other):
# Defer to subclass implementation
return NotImplemented
elif isinstance(other, np.ndarray) and is_timedelta64_dtype(other):
# wrap in Series for op, this will in turn wrap in TimedeltaIndex,
# but will correctly raise TypeError instead of NullFrequencyError
# for add/sub ops
# GH#22390; wrap in Series for op, this will in turn wrap in
# TimedeltaIndex, but will correctly raise TypeError instead of
# NullFrequencyError for add/sub ops
from pandas import Series
other = Series(other)
out = op(self, other)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -598,7 +598,7 @@ def _evaluate_numeric_binop(self, other):
# so we need to catch these explicitly
return op(self._int64index, other)
elif is_timedelta64_dtype(other):
Copy link
Contributor

Choose a reason for hiding this comment

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

doesn't the fall thru raise TypeError?

Copy link
Member Author

Choose a reason for hiding this comment

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

I don’t understand the question

Copy link
Contributor

Choose a reason for hiding this comment

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

your comment is at odds with the checking i think. pls revise comments and/or checks.

Copy link
Member Author
8000

Choose a reason for hiding this comment

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

The comment below this line # must be an np.ndarray; GH#22390 along with the check above elif is_timedelta64_dtype(other) is just saying this is an ndarray["timedelta64['ns']"]. I don't think these are at odds.

# Must be an np.ndarray
# Must be an np.ndarray; GH#22390
return op(self._int64index, other)

other = self._validate_for_numeric_binop(other, op)
Expand Down
11 changes: 6 additions & 5 deletions pandas/core/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -1246,9 +1246,9 @@ def wrapper(left, right):

elif is_timedelta64_dtype(right) and not is_scalar(right):
# i.e. exclude np.timedelta64 object
# Unfortunately we need to special-case right-hand timedelta64
# dtypes because numpy casts integer dtypes to timedelta64 when
# operating with timedelta64
# GH#22390 Unfortunately we need to special-case right-hand
# timedelta64 dtypes because numpy casts integer dtypes to
# timedelta64 when operating with timedelta64
if isinstance(right, np.ndarray):
# upcast to TimedeltaIndex before dispatching
Copy link
Contributor

Choose a reason for hiding this comment

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

uhh this seems like a lot of special casing, any way to make this simpler

Copy link
Member Author

Choose a reason for hiding this comment

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

The only simplification I considered but didn't use was something like:

def maybe_upcast_for_op(obj):
     if type(obj) is timedelta:
        return pd.Timedelta(obj)
    if isinstance(obj, np.ndarray) and is_timedelta64_dtype(obj):
        return pd.TimedeltaIndex(obj)
    return obj

which would go right after get_op_result_name.

Copy link
Contributor

Choose a reason for hiding this comment

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

maybe re-route the scalars to a separate path. This is getting way special casey here.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'll implement the maybe_upcast idea and see if that is prettier

right = pd.TimedeltaIndex(right)
Expand All @@ -1264,8 +1264,9 @@ def wrapper(left, right):
dtype=result.dtype)

elif type(right) is datetime.timedelta:
Copy link
Contributor

Choose a reason for hiding this comment

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

this case you can include above (before what you added), no?

if isintance(right, (datetime.timedelta, Timedelta)):
  right = Timedelta(right)
....

Copy link
Member Author

Choose a reason for hiding this comment

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

The version code above casts to TimedeltaIndex, not Timedelta.

# cast up to Timedelta to rely on Timedelta implementation;
# otherwise operation against numeric-dtype raises TypeError
# GH#22390 cast up to Timedelta to rely on Timedelta
# implementation; otherwise operation against numeric-dtype
# raises TypeError
right = pd.Timedelta(right)
return op(left, right)

Expand Down
2 changes: 2 additions & 0 deletions pandas/tests/arithmetic/test_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class TestNumericArraylikeArithmeticWithTimedeltaLike(object):
for cls in [pd.Series, pd.Index]],
ids=lambda x: type(x).__name__ + str(x.dtype))
def test_mul_td64arr(self, left, box_cls):
# GH#22390
right = np.array([1, 2, 3], dtype='m8[s]')
right = box_cls(right)

Expand All @@ -82,6 +83,7 @@ def test_mul_td64arr(self, left, box_cls):
for cls in [pd.Series, pd.Index]],
ids=lambda x: type(x).__name__ + str(x.dtype))
def test_div_td64arr(self, left, box_cls):
# GH#22390
right = np.array([10, 40, 90], dtype='m8[s]')
right = box_cls(right)

Expand Down
0