From 498d08b62a8c20286f20aa64073af2774b713183 Mon Sep 17 00:00:00 2001 From: Brock Date: Thu, 18 Feb 2021 10:31:33 -0800 Subject: [PATCH] REF: share fillna TDBlock/DTBlock --- pandas/core/internals/blocks.py | 37 ++++++++++++++------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ae019c2f853a1..7b910824c208d 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2048,6 +2048,21 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Blo new_values = values.shift(periods, fill_value=fill_value, axis=axis) return [self.make_block_same_class(new_values)] + def fillna( + self, value, limit=None, inplace: bool = False, downcast=None + ) -> List[Block]: + + if not self._can_hold_element(value) and self.dtype.kind != "m": + # We support filling a DatetimeTZ with a `value` whose timezone + # is different by coercing to object. + # TODO: don't special-case td64 + return self.astype(object).fillna(value, limit, inplace, downcast) + + values = self.array_values() + values = values if inplace else values.copy() + new_values = values.fillna(value=value, limit=limit) + return [self.make_block_same_class(values=new_values)] + class DatetimeLikeBlockMixin(NDArrayBackedExtensionBlock): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" @@ -2134,6 +2149,7 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): fill_value = NaT where = DatetimeBlock.where putmask = DatetimeLikeBlockMixin.putmask + fillna = DatetimeLikeBlockMixin.fillna array_values = ExtensionBlock.array_values @@ -2172,19 +2188,6 @@ def external_values(self): # Avoid FutureWarning in .astype in casting from dt64tz to dt64 return self.values._data - def fillna( - self, value, limit=None, inplace: bool = False, downcast=None - ) -> List[Block]: - # We support filling a DatetimeTZ with a `value` whose timezone - # is different by coercing to object. - if self._can_hold_element(value): - return super().fillna(value, limit, inplace, downcast) - - # different timezones, or a non-tz - return self.astype(object).fillna( - value, limit=limit, inplace=inplace, downcast=downcast - ) - class TimeDeltaBlock(DatetimeLikeBlockMixin): __slots__ = () @@ -2194,14 +2197,6 @@ class TimeDeltaBlock(DatetimeLikeBlockMixin): fill_value = np.timedelta64("NaT", "ns") _dtype = fill_value.dtype - def fillna( - self, value, limit=None, inplace: bool = False, downcast=None - ) -> List[Block]: - values = self.array_values() - values = values if inplace else values.copy() - new_values = values.fillna(value=value, limit=limit) - return [self.make_block_same_class(values=new_values)] - class ObjectBlock(Block): __slots__ = ()