Skip to content

BUG: where behaves badly when dtype of self is datetime or timedelta, and dtype of other is not #9804

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

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.16.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,4 @@ Bug Fixes

- Bug in ``Series.quantile`` on empty Series of type ``Datetime`` or ``Timedelta`` (:issue:`9675`)
- Bug in ``where`` causing incorrect results when upcasting was required (:issue:`9731`)
- Bug in ``where`` when dtype of self is datetime64 or timedelta64, but dtype of other is not
3 changes: 2 additions & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3323,7 +3323,8 @@ def where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
except ValueError:
new_other = np.array(other)

if not (new_other == np.array(other)).all():
matches = (new_other == np.array(other))
if matches is False or not matches.all():
other = np.array(other)

# we can't use our existing dtype
Expand Down
22 changes: 13 additions & 9 deletions pandas/core/internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -1324,13 +1324,11 @@ def _try_fill(self, value):
return value

def _try_coerce_args(self, values, other):
""" provide coercion to our input arguments
we are going to compare vs i8, so coerce to floats
repring NaT with np.nan so nans propagate
values is always ndarray like, other may not be """
""" Coerce values and other to float64, with null values converted to
NaN. values is always ndarray-like, other may not be """
def masker(v):
mask = isnull(v)
v = v.view('i8').astype('float64')
v = v.astype('float64')
v[mask] = np.nan
return v

Expand All @@ -1342,6 +1340,8 @@ def masker(v):
other = _coerce_scalar_to_timedelta_type(other, unit='s', box=False).item()
if other == tslib.iNaT:
other = np.nan
elif lib.isscalar(other):
other = np.float64(other)
else:
other = masker(other)

Expand Down Expand Up @@ -1807,16 +1807,20 @@ def _try_operate(self, values):
return values.view('i8')

def _try_coerce_args(self, values, other):
""" provide coercion to our input arguments
we are going to compare vs i8, so coerce to integer
values is always ndarra like, other may not be """
""" Coerce values and other to dtype 'i8'. NaN and NaT convert to
the smallest i8, and will correctly round-trip to NaT if converted
back in _try_coerce_result. values is always ndarray-like, other
may not be """
values = values.view('i8')

Copy link
Contributor

Choose a reason for hiding this comment

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

I would like to see if we can consolidate some of this logic to com._infer_fill_value (which may need a bit of logic), but I think should work

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure I follow. We already know the source and destination dtypes: datetime64 -> int64 or timedelta64 -> float64. What do we need to infer?

Copy link
Contributor

Choose a reason for hiding this comment

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

its not that we need to infer, my point is that a very similar code block exists in several places in the code base. needs to be consolidated to avoid repeating is again. Pls look thru and see where it is duplicated (e.g. in internals.py as well)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm sorry, I still don't see the common functionality. You're talking about this function:

def _try_coerce_args(self, values, other):
    """ Coerce values and other to dtype 'i8'. NaN and NaT convert to
        the smallest i8, and will correctly round-trip to NaT if converted
        back in _try_coerce_result. values is always ndarray-like, other
        may not be """
    values = values.view('i8')

    if is_null_datelike_scalar(other):
        other = tslib.iNaT
    elif isinstance(other, datetime):
        other = lib.Timestamp(other).asm8.view('i8')
    elif hasattr(other, 'dtype') and com.is_integer_dtype(other):
        other = other.view('i8')
    else:
        other = np.array(other, dtype='i8')

    return values, other

and this one?

def _infer_fill_value(val):
    """
    infer the fill value for the nan/NaT from the provided scalar/ndarray/list-like
    if we are a NaT, return the correct dtyped element to provide proper block construction

    """

    if not is_list_like(val):
        val = [val]
    val = np.array(val,copy=False)
    if is_datetimelike(val):
        return np.array('NaT',dtype=val.dtype)
    elif is_object_dtype(val.dtype):
        dtype = lib.infer_dtype(_ensure_object(val))
        if dtype in ['datetime','datetime64']:
            return np.array('NaT',dtype=_NS_DTYPE)
        elif dtype in ['timedelta','timedelta64']:
            return np.array('NaT',dtype=_TD_DTYPE)
    return np.nan

I haven't seen any code block that looks similar to _try_coerce_args elsewhere either. Could you give an example?

if is_null_datelike_scalar(other):
other = tslib.iNaT
elif isinstance(other, datetime):
other = lib.Timestamp(other).asm8.view('i8')
else:
elif hasattr(other, 'dtype') and com.is_integer_dtype(other):
other = other.view('i8')
else:
other = np.array(other, dtype='i8')

return values, other

Expand Down
42 changes: 42 additions & 0 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1855,6 +1855,48 @@ def test_where_dups(self):
expected = Series([5,11,2,5,11,2],index=[0,1,2,0,1,2])
assert_series_equal(comb, expected)

def test_where_datetime(self):
s = Series(date_range('20130102', periods=2))
expected = Series([10, 10], dtype='datetime64[ns]')
mask = np.array([False, False])

rs = s.where(mask, [10, 10])
assert_series_equal(rs, expected)

rs = s.where(mask, 10)
assert_series_equal(rs, expected)

rs = s.where(mask, 10.0)
assert_series_equal(rs, expected)

rs = s.where(mask, [10.0, 10.0])
assert_series_equal(rs, expected)

rs = s.where(mask, [10.0, np.nan])
expected = Series([10, None], dtype='datetime64[ns]')
assert_series_equal(rs, expected)

def test_where_timedelta(self):
s = Series([1, 2], dtype='timedelta64[ns]')
expected = Series([10, 10], dtype='timedelta64[ns]')
mask = np.array([False, False])

rs = s.where(mask, [10, 10])
assert_series_equal(rs, expected)

rs = s.where(mask, 10)
assert_series_equal(rs, expected)

rs = s.where(mask, 10.0)
assert_series_equal(rs, expected)

rs = s.where(mask, [10.0, 10.0])
assert_series_equal(rs, expected)

rs = s.where(mask, [10.0, np.nan])
expected = Series([10, None], dtype='timedelta64[ns]')
assert_series_equal(rs, expected)

def test_mask(self):
s = Series(np.random.randn(5))
cond = s > 0
Expand Down