Skip to content

Commit 49d2019

Browse files
jbrockmendelWillAyd
authored andcommitted
CLN: internals.blocks cleanup, typing (#27941)
1 parent 3577746 commit 49d2019

File tree

1 file changed

+28
-62
lines changed

1 file changed

+28
-62
lines changed

pandas/core/internals/blocks.py

+28-62
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import numpy as np
99

10-
from pandas._libs import NaT, Timestamp, lib, tslib, tslibs
10+
from pandas._libs import NaT, Timestamp, lib, tslib
1111
import pandas._libs.internals as libinternals
1212
from pandas._libs.tslibs import Timedelta, conversion
1313
from pandas._libs.tslibs.timezones import tz_compare
@@ -407,7 +407,7 @@ def fillna(self, value, limit=None, inplace=False, downcast=None):
407407
return self.copy()
408408

409409
if self._can_hold_element(value):
410-
# equivalent: self._try_coerce_args(value) would not raise
410+
# equivalent: _try_coerce_args(value) would not raise
411411
blocks = self.putmask(mask, value, inplace=inplace)
412412
return self._maybe_downcast(blocks, downcast)
413413

@@ -669,7 +669,7 @@ def convert(
669669

670670
return self.copy() if copy else self
671671

672-
def _can_hold_element(self, element):
672+
def _can_hold_element(self, element: Any) -> bool:
673673
""" require the same dtype as ourselves """
674674
dtype = self.values.dtype.type
675675
tipo = maybe_infer_dtype_type(element)
@@ -857,12 +857,6 @@ def setitem(self, indexer, value):
857857
if self._can_hold_element(value):
858858
value = self._try_coerce_args(value)
859859

860-
# can keep its own dtype
861-
if hasattr(value, "dtype") and is_dtype_equal(values.dtype, value.dtype):
862-
dtype = self.dtype
863-
else:
864-
dtype = "infer"
865-
866860
else:
867861
# current dtype cannot store value, coerce to common dtype
868862
find_dtype = False
@@ -871,15 +865,9 @@ def setitem(self, indexer, value):
871865
dtype = value.dtype
872866
find_dtype = True
873867

874-
elif lib.is_scalar(value):
875-
if isna(value):
876-
# NaN promotion is handled in latter path
877-
dtype = False
878-
else:
879-
dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)
880-
find_dtype = True
881-
else:
882-
dtype = "infer"
868+
elif lib.is_scalar(value) and not isna(value):
869+
dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True)
870+
find_dtype = True
883871

884872
if find_dtype:
885873
dtype = find_common_type([values.dtype, dtype])
@@ -1088,7 +1076,7 @@ def coerce_to_target_dtype(self, other):
10881076
mytz = getattr(self.dtype, "tz", None)
10891077
othertz = getattr(dtype, "tz", None)
10901078

1091-
if str(mytz) != str(othertz):
1079+
if not tz_compare(mytz, othertz):
10921080
return self.astype(object)
10931081

10941082
raise AssertionError(
@@ -1308,7 +1296,7 @@ def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None):
13081296
else:
13091297
return self.make_block_same_class(new_values, new_mgr_locs)
13101298

1311-
def diff(self, n, axis=1):
1299+
def diff(self, n: int, axis: int = 1) -> List["Block"]:
13121300
""" return block for the diff of the values """
13131301
new_values = algos.diff(self.values, n, axis=axis)
13141302
return [self.make_block(values=new_values)]
@@ -1397,7 +1385,7 @@ def func(cond, values, other):
13971385

13981386
if not (
13991387
(self.is_integer or self.is_bool)
1400-
and lib.is_scalar(other)
1388+
and lib.is_float(other)
14011389
and np.isnan(other)
14021390
):
14031391
# np.where will cast integer array to floats in this case
@@ -1450,7 +1438,7 @@ def func(cond, values, other):
14501438

14511439
return result_blocks
14521440

1453-
def equals(self, other):
1441+
def equals(self, other) -> bool:
14541442
if self.dtype != other.dtype or self.shape != other.shape:
14551443
return False
14561444
return array_equivalent(self.values, other.values)
@@ -1830,7 +1818,7 @@ def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None):
18301818

18311819
return self.make_block_same_class(new_values, new_mgr_locs)
18321820

1833-
def _can_hold_element(self, element):
1821+
def _can_hold_element(self, element: Any) -> bool:
18341822
# XXX: We may need to think about pushing this onto the array.
18351823
# We're doing the same as CategoricalBlock here.
18361824
return True
@@ -2000,7 +1988,7 @@ class NumericBlock(Block):
20001988
class FloatOrComplexBlock(NumericBlock):
20011989
__slots__ = ()
20021990

2003-
def equals(self, other):
1991+
def equals(self, other) -> bool:
20041992
if self.dtype != other.dtype or self.shape != other.shape:
20051993
return False
20061994
left, right = self.values, other.values
@@ -2011,7 +1999,7 @@ class FloatBlock(FloatOrComplexBlock):
20111999
__slots__ = ()
20122000
is_float = True
20132001

2014-
def _can_hold_element(self, element):
2002+
def _can_hold_element(self, element: Any) -> bool:
20152003
tipo = maybe_infer_dtype_type(element)
20162004
if tipo is not None:
20172005
return issubclass(tipo.type, (np.floating, np.integer)) and not issubclass(
@@ -2075,7 +2063,7 @@ class ComplexBlock(FloatOrComplexBlock):
20752063
__slots__ = ()
20762064
is_complex = True
20772065

2078-
def _can_hold_element(self, element):
2066+
def _can_hold_element(self, element: Any) -> bool:
20792067
tipo = maybe_infer_dtype_type(element)
20802068
if tipo is not None:
20812069
return issubclass(tipo.type, (np.floating, np.integer, np.complexfloating))
@@ -2092,7 +2080,7 @@ class IntBlock(NumericBlock):
20922080
is_integer = True
20932081
_can_hold_na = False
20942082

2095-
def _can_hold_element(self, element):
2083+
def _can_hold_element(self, element: Any) -> bool:
20962084
tipo = maybe_infer_dtype_type(element)
20972085
if tipo is not None:
20982086
return (
@@ -2182,7 +2170,7 @@ def _astype(self, dtype, **kwargs):
21822170
# delegate
21832171
return super()._astype(dtype=dtype, **kwargs)
21842172

2185-
def _can_hold_element(self, element):
2173+
def _can_hold_element(self, element: Any) -> bool:
21862174
tipo = maybe_infer_dtype_type(element)
21872175
if tipo is not None:
21882176
if self.is_datetimetz:
@@ -2372,41 +2360,19 @@ def _slice(self, slicer):
23722360
return self.values[slicer]
23732361

23742362
def _try_coerce_args(self, other):
2375-
"""
2376-
localize and return i8 for the values
2377-
2378-
Parameters
2379-
----------
2380-
other : ndarray-like or scalar
2381-
2382-
Returns
2383-
-------
2384-
base-type other
2385-
"""
2386-
if is_valid_nat_for_dtype(other, self.dtype):
2387-
other = np.datetime64("NaT", "ns")
2388-
elif isinstance(other, self._holder):
2389-
if not tz_compare(other.tz, self.values.tz):
2390-
raise ValueError("incompatible or non tz-aware value")
2391-
2392-
elif isinstance(other, (np.datetime64, datetime, date)):
2393-
other = tslibs.Timestamp(other)
2394-
2395-
# test we can have an equal time zone
2396-
if not tz_compare(other.tz, self.values.tz):
2397-
raise ValueError("incompatible or non tz-aware value")
2398-
else:
2399-
raise TypeError(other)
2400-
2363+
# DatetimeArray handles this for us
24012364
return other
24022365

2403-
def diff(self, n, axis=0):
2404-
"""1st discrete difference
2366+
def diff(self, n: int, axis: int = 0) -> List["Block"]:
2367+
"""
2368+
1st discrete difference.
24052369
24062370
Parameters
24072371
----------
2408-
n : int, number of periods to diff
2409-
axis : int, axis to diff upon. default 0
2372+
n : int
2373+
Number of periods to diff.
2374+
axis : int, default 0
2375+
Axis to diff upon.
24102376
24112377
Returns
24122378
-------
@@ -2468,7 +2434,7 @@ def setitem(self, indexer, value):
24682434
)
24692435
return newb.setitem(indexer, value)
24702436

2471-
def equals(self, other):
2437+
def equals(self, other) -> bool:
24722438
# override for significant performance improvement
24732439
if self.dtype != other.dtype or self.shape != other.shape:
24742440
return False
@@ -2507,7 +2473,7 @@ def __init__(self, values, placement, ndim=None):
25072473
def _holder(self):
25082474
return TimedeltaArray
25092475

2510-
def _can_hold_element(self, element):
2476+
def _can_hold_element(self, element: Any) -> bool:
25112477
tipo = maybe_infer_dtype_type(element)
25122478
if tipo is not None:
25132479
return issubclass(tipo.type, np.timedelta64)
@@ -2600,7 +2566,7 @@ class BoolBlock(NumericBlock):
26002566
is_bool = True
26012567
_can_hold_na = False
26022568

2603-
def _can_hold_element(self, element):
2569+
def _can_hold_element(self, element: Any) -> bool:
26042570
tipo = maybe_infer_dtype_type(element)
26052571
if tipo is not None:
26062572
return issubclass(tipo.type, np.bool_)
@@ -2694,7 +2660,7 @@ def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"]
26942660
# split and convert the blocks
26952661
return _extend_blocks([b.convert(datetime=True, numeric=False) for b in blocks])
26962662

2697-
def _can_hold_element(self, element):
2663+
def _can_hold_element(self, element: Any) -> bool:
26982664
return True
26992665

27002666
def _try_coerce_args(self, other):

0 commit comments

Comments
 (0)