Skip to content

BUG: .item() incorrectly casts td64/dt64 to int #38512

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 1 commit into from
Dec 16, 2020
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: 1 addition & 1 deletion pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -733,7 +733,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj,
raise ValueError(msg)

dtype = val.dtype
val = val.item()
val = lib.item_from_zerodim(val)

elif isinstance(val, str):

Expand Down
3 changes: 2 additions & 1 deletion pandas/core/tools/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import numpy as np

from pandas._libs import lib
from pandas._libs.tslibs import NaT
from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit

Expand Down Expand Up @@ -117,7 +118,7 @@ def to_timedelta(arg, unit=None, errors="raise"):
return _convert_listlike(arg, unit=unit, errors=errors, name=arg.name)
elif isinstance(arg, np.ndarray) and arg.ndim == 0:
# extract array scalar and process below
arg = arg.item()
arg = lib.item_from_zerodim(arg)
elif is_list_like(arg) and getattr(arg, "ndim", 1) == 1:
return _convert_listlike(arg, unit=unit, errors=errors)
elif getattr(arg, "ndim", 1) > 1:
Expand Down
20 changes: 19 additions & 1 deletion pandas/tests/dtypes/cast/test_infer_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
import numpy as np
import pytest

from pandas.core.dtypes.cast import infer_dtype_from_array, infer_dtype_from_scalar
from pandas.core.dtypes.cast import (
infer_dtype_from,
infer_dtype_from_array,
infer_dtype_from_scalar,
)
from pandas.core.dtypes.common import is_dtype_equal

from pandas import (
Expand Down Expand Up @@ -171,3 +175,17 @@ def test_infer_dtype_from_scalar_errors():
def test_infer_dtype_from_array(arr, expected, pandas_dtype):
dtype, _ = infer_dtype_from_array(arr, pandas_dtype=pandas_dtype)
assert is_dtype_equal(dtype, expected)


@pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64])
def test_infer_dtype_from_scalar_zerodim_datetimelike(cls):
# ndarray.item() can incorrectly return int instead of td64/dt64
val = cls(1234, "ns")
arr = np.array(val)

dtype, res = infer_dtype_from_scalar(arr)
assert dtype.type is cls
assert isinstance(res, cls)

dtype, res = infer_dtype_from(arr)
assert dtype.type is cls
17 changes: 17 additions & 0 deletions pandas/tests/tools/test_to_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,20 @@ def test_to_timedelta_precision_over_nanos(self, input, expected, func):
expected = pd.Timedelta(expected)
result = func(input)
assert result == expected

def test_to_timedelta_zerodim(self):
# ndarray.item() incorrectly returns int for dt64[ns] and td64[ns]
dt64 = pd.Timestamp.now().to_datetime64()
arg = np.array(dt64)

msg = (
"Value must be Timedelta, string, integer, float, timedelta "
"or convertible, not datetime64"
)
with pytest.raises(ValueError, match=msg):
to_timedelta(arg)

arg2 = arg.view("m8[ns]")
result = to_timedelta(arg2)
assert isinstance(result, pd.Timedelta)
assert result.value == dt64.view("i8")