Skip to content

BUG: setting td64 value into Series[numeric] #39086

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 4 commits into from
Jan 11, 2021
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 doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ Indexing
- Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` with empty :class:`DataFrame` and specified columns for string indexer and non empty :class:`DataFrame` to set (:issue:`38831`)
- Bug in :meth:`DataFrame.iloc.__setitem__` and :meth:`DataFrame.loc.__setitem__` with mixed dtypes when setting with a dictionary value (:issue:`38335`)
- Bug in :meth:`DataFrame.loc` dropping levels of :class:`MultiIndex` when :class:`DataFrame` used as input has only one row (:issue:`10521`)
-
- Bug in setting ``timedelta64`` values into numeric :class:`Series` failing to cast to object dtype (:issue:`39086`)

Missing
^^^^^^^
Expand Down
12 changes: 6 additions & 6 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1874,9 +1874,9 @@ def validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None:
):
raise ValueError("Cannot assign nan to integer series")

if (
issubclass(dtype.type, (np.integer, np.floating, complex))
and not issubclass(dtype.type, np.bool_)
and is_bool(value)
):
raise ValueError("Cannot assign bool to float/integer series")
if dtype.kind in ["i", "u", "f", "c"]:
if is_bool(value) or isinstance(value, np.timedelta64):
# numpy will cast td64 to integer if we're not careful
raise ValueError(
f"Cannot assign {type(value).__name__} to float/integer series"
)
14 changes: 5 additions & 9 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,11 +678,7 @@ def convert(

def _can_hold_element(self, element: Any) -> bool:
""" require the same dtype as ourselves """
dtype = self.values.dtype.type
tipo = maybe_infer_dtype_type(element)
if tipo is not None:
return issubclass(tipo.type, dtype)
return isinstance(element, dtype)
raise NotImplementedError("Implemented on subclasses")

def should_store(self, value: ArrayLike) -> bool:
"""
Expand Down Expand Up @@ -1969,10 +1965,10 @@ class ComplexBlock(NumericBlock):
def _can_hold_element(self, element: Any) -> bool:
tipo = maybe_infer_dtype_type(element)
if tipo is not None:
return issubclass(tipo.type, (np.floating, np.integer, np.complexfloating))
return isinstance(
element, (float, int, complex, np.float_, np.int_)
) and not isinstance(element, (bool, np.bool_))
return tipo.kind in ["c", "f", "i", "u"]
return (
lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element)
)


class IntBlock(NumericBlock):
Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/series/indexing/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,3 +395,27 @@ def test_setitem_slice_into_readonly_backing_data():
series[1:3] = 1

assert not array.any()


@pytest.mark.parametrize(
"key", [0, slice(0, 1), [0], np.array([0]), range(1)], ids=type
)
@pytest.mark.parametrize("dtype", [complex, int, float])
def test_setitem_td64_into_complex(key, dtype, indexer_sli):
# timedelta64 should not be treated as integers
arr = np.arange(5).astype(dtype)
ser = Series(arr)
td = np.timedelta64(4, "ns")

indexer_sli(ser)[key] = td
assert ser.dtype == object
assert arr[0] == 0 # original array is unchanged

if not isinstance(key, int) and not (
indexer_sli is tm.loc and isinstance(key, slice)
):
# skip key/indexer_sli combinations that will have mismatched lengths
ser = Series(arr)
indexer_sli(ser)[key] = np.full((1,), td)
assert ser.dtype == object
assert arr[0] == 0 # original array is unchanged