From 5c757e9c4cf6a74fabfa1983dcd72b4759a88e5f Mon Sep 17 00:00:00 2001 From: jbrockmendel Date: Wed, 2 Feb 2022 19:08:36 -0800 Subject: [PATCH] REF: use np_can_hold_element pattern in Block.shift (#45792) --- pandas/core/internals/blocks.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 06c1ae878b8ec..e01a31c0a20af 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1138,14 +1138,16 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Blo fill_value = self._standardize_fill_value(fill_value) - if not self._can_hold_element(fill_value): + try: + casted = np_can_hold_element(self.dtype, fill_value) + except LossySetitemError: nb = self.coerce_to_target_dtype(fill_value) return nb.shift(periods, axis=axis, fill_value=fill_value) - values = cast(np.ndarray, self.values) - new_values = shift(values, periods, axis, fill_value) - - return [self.make_block(new_values)] + else: + values = cast(np.ndarray, self.values) + new_values = shift(values, periods, axis, casted) + return [self.make_block(new_values)] def where(self, other, cond) -> list[Block]: """