Skip to content

BUG: fix+test assigning invalid NAT-like to DTA/TDA/PA #27331

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 8 commits into from
Jul 11, 2019
7 changes: 5 additions & 2 deletions pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
)
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
from pandas.core.dtypes.inference import is_array_like
from pandas.core.dtypes.missing import isna
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna

from pandas._typing import DatetimeLikeScalar
from pandas.core import missing, nanops
Expand Down Expand Up @@ -492,7 +492,10 @@ def __setitem__(
elif isinstance(value, self._scalar_type):
self._check_compatible_with(value)
value = self._unbox_scalar(value)
elif isna(value) or value == iNaT:
elif is_valid_nat_for_dtype(value, self.dtype):
value = iNaT
elif not isna(value) and lib.is_integer(value) and value == iNaT:
# exclude misc e.g. object() and any NAs not allowed above
value = iNaT
else:
msg = (
Expand Down
24 changes: 24 additions & 0 deletions pandas/core/dtypes/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,3 +559,27 @@ def remove_na_arraylike(arr):
return arr[notna(arr)]
else:
return arr[notna(lib.values_from_object(arr))]


def is_valid_nat_for_dtype(obj, dtype):
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 type these(followup ok)

"""
isna check that excludes incompatible dtypes
Parameters
----------
obj : object
dtype : np.datetime64, np.timedelta64, DatetimeTZDtype, or PeriodDtype
Returns
-------
bool
"""
if not isna(obj):
return False
if dtype.kind == "M":
return not isinstance(obj, np.timedelta64)
if dtype.kind == "m":
return not isinstance(obj, np.datetime64)

# must be PeriodDType
return not isinstance(obj, (np.datetime64, np.timedelta64))
48 changes: 48 additions & 0 deletions pandas/tests/arrays/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,3 +651,51 @@ def test_array_interface(self, period_index):
result = np.asarray(arr, dtype="S20")
expected = np.asarray(arr).astype("S20")
tm.assert_numpy_array_equal(result, expected)

Copy link
Contributor

Choose a reason for hiding this comment

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

are there other setitem tests? put near those


@pytest.mark.parametrize(
"array,casting_nats",
[
(
pd.TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
(pd.NaT, np.timedelta64("NaT", "ns")),
),
(
pd.date_range("2000-01-01", periods=3, freq="D")._data,
(pd.NaT, np.datetime64("NaT", "ns")),
),
(pd.period_range("2000-01-01", periods=3, freq="D")._data, (pd.NaT,)),
],
ids=lambda x: type(x).__name__,
)
def test_casting_nat_setitem_array(array, casting_nats):
expected = type(array)._from_sequence([pd.NaT, array[1], array[2]])

for nat in casting_nats:
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 make another level of parameterization to make these truly separate tests?

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 think so; the casting_nats parameter depends on the array parameter.

I've been looking at pytest extensions that might make this kind of thing possible

arr = array.copy()
arr[0] = nat
tm.assert_equal(arr, expected)


@pytest.mark.parametrize(
"array,non_casting_nats",
[
(
pd.TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data,
(np.datetime64("NaT", "ns"),),
),
(
pd.date_range("2000-01-01", periods=3, freq="D")._data,
(np.timedelta64("NaT", "ns"),),
),
(
pd.period_range("2000-01-01", periods=3, freq="D")._data,
(np.datetime64("NaT", "ns"), np.timedelta64("NaT", "ns")),
),
],
ids=lambda x: type(x).__name__,
)
def test_invalid_nat_setitem_array(array, non_casting_nats):
for nat in non_casting_nats:
with pytest.raises(TypeError):
array[0] = nat