Skip to content

REF: implement dtypes.cast.can_hold_element #39094

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 2 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
43 changes: 43 additions & 0 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1880,3 +1880,46 @@ def validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None:
raise ValueError(
f"Cannot assign {type(value).__name__} to float/integer series"
)


def can_hold_element(dtype: np.dtype, element: Any) -> bool:
"""
Can we do an inplace setitem with this element in an array with this dtype?

Parameters
----------
dtype : np.dtype
element : Any

Returns
-------
bool
"""
tipo = maybe_infer_dtype_type(element)

if dtype.kind in ["i", "u"]:
if tipo is not None:
return tipo.kind in ["i", "u"] and dtype.itemsize >= tipo.itemsize

# We have not inferred an integer from the dtype
# check if we have a builtin int or a float equal to an int
return is_integer(element) or (is_float(element) and element.is_integer())

elif dtype.kind == "f":
if tipo is not None:
return tipo.kind in ["f", "i", "u"]
return lib.is_integer(element) or lib.is_float(element)

elif dtype.kind == "c":
if tipo is not None:
return tipo.kind in ["c", "f", "i", "u"]
return (
lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element)
)

elif dtype.kind == "b":
if tipo is not None:
return tipo.kind == "b"
return lib.is_bool(element)

raise NotImplementedError(dtype)
44 changes: 4 additions & 40 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from pandas.core.dtypes.cast import (
astype_dt64_to_dt64tz,
astype_nansafe,
can_hold_element,
convert_scalar_for_putitemlike,
find_common_type,
infer_dtype_from,
Expand All @@ -40,7 +41,6 @@
is_datetime64tz_dtype,
is_dtype_equal,
is_extension_array_dtype,
is_float,
is_integer,
is_list_like,
is_object_dtype,
Expand Down Expand Up @@ -1906,24 +1906,14 @@ class NumericBlock(Block):
is_numeric = True
_can_hold_na = True

def _can_hold_element(self, element: Any) -> bool:
return can_hold_element(self.dtype, element)


class FloatBlock(NumericBlock):
__slots__ = ()
is_float = True

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)) and not issubclass(
tipo.type, np.timedelta64
)
return isinstance(
element, (float, int, np.floating, np.int_)
) and not isinstance(
element,
(bool, np.bool_, np.timedelta64),
)

def to_native_types(
self, na_rep="", float_format=None, decimal=".", quoting=None, **kwargs
):
Expand Down Expand Up @@ -1962,32 +1952,12 @@ class ComplexBlock(NumericBlock):
__slots__ = ()
is_complex = True

def _can_hold_element(self, element: Any) -> bool:
tipo = maybe_infer_dtype_type(element)
if tipo is not None:
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):
__slots__ = ()
is_integer = True
_can_hold_na = False

def _can_hold_element(self, element: Any) -> bool:
tipo = maybe_infer_dtype_type(element)
if tipo is not None:
return (
issubclass(tipo.type, np.integer)
and not issubclass(tipo.type, np.timedelta64)
and self.dtype.itemsize >= tipo.itemsize
)
# We have not inferred an integer from the dtype
# check if we have a builtin int or a float equal to an int
return is_integer(element) or (is_float(element) and element.is_integer())


class DatetimeLikeBlockMixin(Block):
"""Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock."""
Expand Down Expand Up @@ -2284,12 +2254,6 @@ class BoolBlock(NumericBlock):
is_bool = True
_can_hold_na = False

def _can_hold_element(self, element: Any) -> bool:
tipo = maybe_infer_dtype_type(element)
if tipo is not None:
return issubclass(tipo.type, np.bool_)
return isinstance(element, (bool, np.bool_))


class ObjectBlock(Block):
__slots__ = ()
Expand Down