Skip to content

Commit eff369d

Browse files
jbrockmendelim-vinicius
authored and
im-vinicius
committed
CLN: assorted (pandas-dev#53932)
1 parent cc38032 commit eff369d

File tree

14 files changed

+32
-56
lines changed

14 files changed

+32
-56
lines changed

pandas/_libs/lib.pyi

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ NoDefault = Literal[_NoDefault.no_default]
3636
i8max: int
3737
u8max: int
3838

39-
def is_np_dtype(dtype: object, kinds: str | None = ...) -> bool: ...
39+
def is_np_dtype(dtype: object, kinds: str | None = ...) -> TypeGuard[np.dtype]: ...
4040
def item_from_zerodim(val: object) -> object: ...
4141
def infer_dtype(value: object, skipna: bool = ...) -> str: ...
4242
def is_iterator(obj: object) -> bool: ...

pandas/core/array_algos/take.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def take_nd(
9595
"""
9696
if fill_value is lib.no_default:
9797
fill_value = na_value_for_dtype(arr.dtype, compat=False)
98-
elif isinstance(arr.dtype, np.dtype) and arr.dtype.kind in "mM":
98+
elif lib.is_np_dtype(arr.dtype, "mM"):
9999
dtype, fill_value = maybe_promote(arr.dtype, fill_value)
100100
if arr.dtype != dtype:
101101
# EA.take is strict about returning a new object of the same type

pandas/core/arrays/timedeltas.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ def _simple_new( # type: ignore[override]
217217
dtype: np.dtype[np.timedelta64] = TD64NS_DTYPE,
218218
) -> Self:
219219
# Require td64 dtype, not unit-less, matching values.dtype
220-
assert isinstance(dtype, np.dtype) and dtype.kind == "m"
220+
assert lib.is_np_dtype(dtype, "m")
221221
assert not tslibs.is_unitless(dtype)
222222
assert isinstance(values, np.ndarray), type(values)
223223
assert dtype == values.dtype
@@ -363,7 +363,7 @@ def astype(self, dtype, copy: bool = True):
363363
# DatetimeLikeArrayMixin super call handles other cases
364364
dtype = pandas_dtype(dtype)
365365

366-
if isinstance(dtype, np.dtype) and dtype.kind == "m":
366+
if lib.is_np_dtype(dtype, "m"):
367367
if dtype == self.dtype:
368368
if copy:
369369
return self.copy()

pandas/core/construction.py

+2-12
Original file line numberDiff line numberDiff line change
@@ -364,19 +364,9 @@ def array(
364364
# 1. datetime64[ns,us,ms,s]
365365
# 2. timedelta64[ns,us,ms,s]
366366
# so that a DatetimeArray is returned.
367-
if (
368-
lib.is_np_dtype(dtype, "M")
369-
# error: Argument 1 to "py_get_unit_from_dtype" has incompatible type
370-
# "Optional[dtype[Any]]"; expected "dtype[Any]"
371-
and is_supported_unit(get_unit_from_dtype(dtype)) # type: ignore[arg-type]
372-
):
367+
if lib.is_np_dtype(dtype, "M") and is_supported_unit(get_unit_from_dtype(dtype)):
373368
return DatetimeArray._from_sequence(data, dtype=dtype, copy=copy)
374-
if (
375-
lib.is_np_dtype(dtype, "m")
376-
# error: Argument 1 to "py_get_unit_from_dtype" has incompatible type
377-
# "Optional[dtype[Any]]"; expected "dtype[Any]"
378-
and is_supported_unit(get_unit_from_dtype(dtype)) # type: ignore[arg-type]
379-
):
369+
if lib.is_np_dtype(dtype, "m") and is_supported_unit(get_unit_from_dtype(dtype)):
380370
return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy)
381371

382372
return PandasArray._from_sequence(data, dtype=dtype, copy=copy)

pandas/core/dtypes/cast.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1325,7 +1325,7 @@ def common_dtype_categorical_compat(
13251325
# GH#38240
13261326

13271327
# TODO: more generally, could do `not can_hold_na(dtype)`
1328-
if isinstance(dtype, np.dtype) and dtype.kind in "iu":
1328+
if lib.is_np_dtype(dtype, "iu"):
13291329
for obj in objs:
13301330
# We don't want to accientally allow e.g. "categorical" str here
13311331
obj_dtype = getattr(obj, "dtype", None)
@@ -1502,7 +1502,7 @@ def construct_1d_arraylike_from_scalar(
15021502
if length and dtype.kind in "iu" and isna(value):
15031503
# coerce if we have nan for an integer dtype
15041504
dtype = np.dtype("float64")
1505-
elif isinstance(dtype, np.dtype) and dtype.kind in "US":
1505+
elif lib.is_np_dtype(dtype, "US"):
15061506
# we need to coerce to object dtype to avoid
15071507
# to allow numpy to take our string as a scalar value
15081508
dtype = np.dtype("object")

pandas/core/dtypes/common.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -890,9 +890,7 @@ def is_datetime64_any_dtype(arr_or_dtype) -> bool:
890890
tipo = _get_dtype(arr_or_dtype)
891891
except TypeError:
892892
return False
893-
return (isinstance(tipo, np.dtype) and tipo.kind == "M") or isinstance(
894-
tipo, DatetimeTZDtype
895-
)
893+
return lib.is_np_dtype(tipo, "M") or isinstance(tipo, DatetimeTZDtype)
896894

897895

898896
def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
@@ -1329,9 +1327,7 @@ def is_ea_or_datetimelike_dtype(dtype: DtypeObj | None) -> bool:
13291327
-----
13301328
Checks only for dtype objects, not dtype-castable strings or types.
13311329
"""
1332-
return isinstance(dtype, ExtensionDtype) or (
1333-
isinstance(dtype, np.dtype) and dtype.kind in "mM"
1334-
)
1330+
return isinstance(dtype, ExtensionDtype) or (lib.is_np_dtype(dtype, "mM"))
13351331

13361332

13371333
def is_complex_dtype(arr_or_dtype) -> bool:

pandas/core/dtypes/missing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -749,10 +749,10 @@ def isna_all(arr: ArrayLike) -> bool:
749749
chunk_len = max(total_len // 40, 1000)
750750

751751
dtype = arr.dtype
752-
if dtype.kind == "f" and isinstance(dtype, np.dtype):
752+
if lib.is_np_dtype(dtype, "f"):
753753
checker = nan_checker
754754

755-
elif (isinstance(dtype, np.dtype) and dtype.kind in "mM") or isinstance(
755+
elif (lib.is_np_dtype(dtype, "mM")) or isinstance(
756756
dtype, (DatetimeTZDtype, PeriodDtype)
757757
):
758758
# error: Incompatible types in assignment (expression has type

pandas/core/interchange/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def dtype_to_arrow_c_fmt(dtype: DtypeObj) -> str:
135135
if lib.is_np_dtype(dtype, "M"):
136136
# Selecting the first char of resolution string:
137137
# dtype.str -> '<M8[ns]'
138-
resolution = re.findall(r"\[(.*)\]", typing.cast(np.dtype, dtype).str)[0][:1]
138+
resolution = re.findall(r"\[(.*)\]", dtype.str)[0][:1]
139139
return ArrowCTypes.TIMESTAMP.format(resolution=resolution, tz="")
140140

141141
raise NotImplementedError(

pandas/core/internals/array_manager.py

+3-9
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,7 @@ def apply(
220220
assert "filter" not in kwargs
221221

222222
align_keys = align_keys or []
223-
result_arrays: list[np.ndarray] = []
223+
result_arrays: list[ArrayLike] = []
224224
# fillna: Series/DataFrame is responsible for making sure value is aligned
225225

226226
aligned_args = {k: kwargs[k] for k in align_keys}
@@ -247,16 +247,10 @@ def apply(
247247
else:
248248
applied = getattr(arr, f)(**kwargs)
249249

250-
# if not isinstance(applied, ExtensionArray):
251-
# # TODO not all EA operations return new EAs (eg astype)
252-
# applied = array(applied)
253250
result_arrays.append(applied)
254251

255252
new_axes = self._axes
256-
257-
# error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]";
258-
# expected "List[Union[ndarray, ExtensionArray]]"
259-
return type(self)(result_arrays, new_axes) # type: ignore[arg-type]
253+
return type(self)(result_arrays, new_axes)
260254

261255
def apply_with_block(self, f, align_keys=None, **kwargs) -> Self:
262256
# switch axis to follow BlockManager logic
@@ -1319,7 +1313,7 @@ def concat_arrays(to_concat: list) -> ArrayLike:
13191313

13201314
if single_dtype:
13211315
target_dtype = to_concat_no_proxy[0].dtype
1322-
elif all(x.kind in "iub" and isinstance(x, np.dtype) for x in dtypes):
1316+
elif all(lib.is_np_dtype(x, "iub") for x in dtypes):
13231317
# GH#42092
13241318
target_dtype = np_find_common_type(*dtypes)
13251319
else:

pandas/core/internals/blocks.py

+9
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,7 @@ def _downcast_2d(self, dtype, using_cow: bool = False) -> list[Block]:
463463
refs = self.refs if using_cow and new_values is self.values else None
464464
return [self.make_block(new_values, refs=refs)]
465465

466+
@final
466467
def convert(
467468
self,
468469
*,
@@ -951,6 +952,7 @@ def set_inplace(self, locs, values: ArrayLike, copy: bool = False) -> None:
951952
self.values = self.values.copy()
952953
self.values[locs] = values
953954

955+
@final
954956
def take_nd(
955957
self,
956958
indexer: npt.NDArray[np.intp],
@@ -1632,6 +1634,7 @@ class EABackedBlock(Block):
16321634

16331635
values: ExtensionArray
16341636

1637+
@final
16351638
def shift(self, periods: int, fill_value: Any = None) -> list[Block]:
16361639
"""
16371640
Shift the block by `periods`.
@@ -1644,6 +1647,7 @@ def shift(self, periods: int, fill_value: Any = None) -> list[Block]:
16441647
new_values = self.values.T.shift(periods=periods, fill_value=fill_value).T
16451648
return [self.make_block_same_class(new_values)]
16461649

1650+
@final
16471651
def setitem(self, indexer, value, using_cow: bool = False):
16481652
"""
16491653
Attempt self.values[indexer] = value, possibly creating a new array.
@@ -1702,6 +1706,7 @@ def setitem(self, indexer, value, using_cow: bool = False):
17021706
else:
17031707
return self
17041708

1709+
@final
17051710
def where(
17061711
self, other, cond, _downcast: str | bool = "infer", using_cow: bool = False
17071712
) -> list[Block]:
@@ -1772,6 +1777,7 @@ def where(
17721777
nb = self.make_block_same_class(res_values)
17731778
return [nb]
17741779

1780+
@final
17751781
def putmask(self, mask, new, using_cow: bool = False) -> list[Block]:
17761782
"""
17771783
See Block.putmask.__doc__
@@ -1839,6 +1845,7 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]:
18391845

18401846
return [self]
18411847

1848+
@final
18421849
def delete(self, loc) -> list[Block]:
18431850
# This will be unnecessary if/when __array_function__ is implemented
18441851
if self.ndim == 1:
@@ -1850,10 +1857,12 @@ def delete(self, loc) -> list[Block]:
18501857
return []
18511858
return super().delete(loc)
18521859

1860+
@final
18531861
@cache_readonly
18541862
def array_values(self) -> ExtensionArray:
18551863
return self.values
18561864

1865+
@final
18571866
def get_values(self, dtype: DtypeObj | None = None) -> np.ndarray:
18581867
"""
18591868
return object dtype as boxed values, such as Timestamps/Timedelta

pandas/core/internals/managers.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -1607,11 +1607,7 @@ def as_array(
16071607
if na_value is not lib.no_default:
16081608
# We want to copy when na_value is provided to avoid
16091609
# mutating the original object
1610-
if (
1611-
isinstance(blk.dtype, np.dtype)
1612-
and blk.dtype.kind == "f"
1613-
and passed_nan
1614-
):
1610+
if lib.is_np_dtype(blk.dtype, "f") and passed_nan:
16151611
# We are already numpy-float and na_value=np.nan
16161612
pass
16171613
else:

pandas/core/tools/datetimes.py

-1
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,6 @@ def _convert_listlike_datetimes(
404404
return arg
405405

406406
elif lib.is_np_dtype(arg_dtype, "M"):
407-
arg_dtype = cast(np.dtype, arg_dtype)
408407
if not is_supported_unit(get_unit_from_dtype(arg_dtype)):
409408
# We go to closest supported reso, i.e. "s"
410409
arg = astype_overflowsafe(

pandas/tests/indexes/test_setops.py

+4-12
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import numpy as np
99
import pytest
1010

11+
from pandas._libs import lib
12+
1113
from pandas.core.dtypes.cast import find_common_type
1214

1315
from pandas import (
@@ -67,18 +69,8 @@ def test_union_different_types(index_flat, index_flat2, request):
6769
warn = None
6870
if not len(idx1) or not len(idx2):
6971
pass
70-
elif (
71-
idx1.dtype.kind == "c"
72-
and (
73-
idx2.dtype.kind not in ["i", "u", "f", "c"]
74-
or not isinstance(idx2.dtype, np.dtype)
75-
)
76-
) or (
77-
idx2.dtype.kind == "c"
78-
and (
79-
idx1.dtype.kind not in ["i", "u", "f", "c"]
80-
or not isinstance(idx1.dtype, np.dtype)
81-
)
72+
elif (idx1.dtype.kind == "c" and (not lib.is_np_dtype(idx2.dtype, "iufc"))) or (
73+
idx2.dtype.kind == "c" and (not lib.is_np_dtype(idx1.dtype, "iufc"))
8274
):
8375
# complex objects non-sortable
8476
warn = RuntimeWarning

pandas/tests/reshape/merge/test_merge_asof.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1518,7 +1518,7 @@ def test_merge_asof_index_behavior(kwargs):
15181518
tm.assert_frame_equal(result, expected)
15191519

15201520

1521-
def test_merge_asof_numeri_column_in_index():
1521+
def test_merge_asof_numeric_column_in_index():
15221522
# GH#34488
15231523
left = pd.DataFrame({"b": [10, 11, 12]}, index=Index([1, 2, 3], name="a"))
15241524
right = pd.DataFrame({"c": [20, 21, 22]}, index=Index([0, 2, 3], name="a"))
@@ -1528,7 +1528,7 @@ def test_merge_asof_numeri_column_in_index():
15281528
tm.assert_frame_equal(result, expected)
15291529

15301530

1531-
def test_merge_asof_numeri_column_in_multiindex():
1531+
def test_merge_asof_numeric_column_in_multiindex():
15321532
# GH#34488
15331533
left = pd.DataFrame(
15341534
{"b": [10, 11, 12]},

0 commit comments

Comments
 (0)