Skip to content

Commit 2635b51

Browse files
mroeschkeyehoshuadimarsky
authored andcommitted
TYP: Fix typing errors on main (pandas-dev#47469)
1 parent 91cf2d8 commit 2635b51

File tree

22 files changed

+137
-85
lines changed

22 files changed

+137
-85
lines changed

pandas/core/algorithms.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1064,7 +1064,13 @@ def checked_add_with_arr(
10641064
elif arr_mask is not None:
10651065
not_nan = np.logical_not(arr_mask)
10661066
elif b_mask is not None:
1067-
not_nan = np.logical_not(b2_mask)
1067+
# error: Argument 1 to "__call__" of "_UFunc_Nin1_Nout1" has
1068+
# incompatible type "Optional[ndarray[Any, dtype[bool_]]]";
1069+
# expected "Union[_SupportsArray[dtype[Any]], _NestedSequence
1070+
# [_SupportsArray[dtype[Any]]], bool, int, float, complex, str
1071+
# , bytes, _NestedSequence[Union[bool, int, float, complex, str
1072+
# , bytes]]]"
1073+
not_nan = np.logical_not(b2_mask) # type: ignore[arg-type]
10681074
else:
10691075
not_nan = np.empty(arr.shape, dtype=bool)
10701076
not_nan.fill(True)

pandas/core/array_algos/quantile.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,10 @@ def _nanpercentile_1d(
143143
return np.percentile(
144144
values,
145145
qs,
146-
**{np_percentile_argname: interpolation},
146+
# error: No overload variant of "percentile" matches argument
147+
# types "ndarray[Any, Any]", "ndarray[Any, dtype[floating[_64Bit]]]"
148+
# , "Dict[str, str]" [call-overload]
149+
**{np_percentile_argname: interpolation}, # type: ignore[call-overload]
147150
)
148151

149152

@@ -212,5 +215,8 @@ def _nanpercentile(
212215
values,
213216
qs,
214217
axis=1,
215-
**{np_percentile_argname: interpolation},
218+
# error: No overload variant of "percentile" matches argument types
219+
# "ndarray[Any, Any]", "ndarray[Any, dtype[floating[_64Bit]]]",
220+
# "int", "Dict[str, str]" [call-overload]
221+
**{np_percentile_argname: interpolation}, # type: ignore[call-overload]
216222
)

pandas/core/arraylike.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -265,9 +265,8 @@ def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any)
265265
return result
266266

267267
# Determine if we should defer.
268-
# error: "Type[ndarray[Any, Any]]" has no attribute "__array_ufunc__"
269268
no_defer = (
270-
np.ndarray.__array_ufunc__, # type: ignore[attr-defined]
269+
np.ndarray.__array_ufunc__,
271270
cls.__array_ufunc__,
272271
)
273272

pandas/core/arrays/arrow/array.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,15 @@ def _indexing_key_to_indices(
496496
if isinstance(key, slice):
497497
indices = np.arange(n)[key]
498498
elif is_integer(key):
499-
indices = np.arange(n)[[key]]
499+
# error: Invalid index type "List[Union[int, ndarray[Any, Any]]]"
500+
# for "ndarray[Any, dtype[signedinteger[Any]]]"; expected type
501+
# "Union[SupportsIndex, _SupportsArray[dtype[Union[bool_,
502+
# integer[Any]]]], _NestedSequence[_SupportsArray[dtype[Union
503+
# [bool_, integer[Any]]]]], _NestedSequence[Union[bool, int]]
504+
# , Tuple[Union[SupportsIndex, _SupportsArray[dtype[Union[bool_
505+
# , integer[Any]]]], _NestedSequence[_SupportsArray[dtype[Union
506+
# [bool_, integer[Any]]]]], _NestedSequence[Union[bool, int]]], ...]]"
507+
indices = np.arange(n)[[key]] # type: ignore[index]
500508
elif is_bool_dtype(key):
501509
key = np.asarray(key)
502510
if len(key) != n:

pandas/core/arrays/datetimes.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -487,10 +487,7 @@ def _generate_range(
487487
np.linspace(0, end.value - start.value, periods, dtype="int64")
488488
+ start.value
489489
)
490-
# error: Non-overlapping equality check
491-
# (left operand type: "dtype[signedinteger[Any]]",
492-
# right operand type: "Literal['i8']")
493-
if i8values.dtype != "i8": # type: ignore[comparison-overlap]
490+
if i8values.dtype != "i8":
494491
# 2022-01-09 I (brock) am not sure if it is possible for this
495492
# to overflow and cast to e.g. f8, but if it does we need to cast
496493
i8values = i8values.astype("i8")

pandas/core/arrays/interval.py

+9-16
Original file line numberDiff line numberDiff line change
@@ -687,21 +687,7 @@ def __getitem__(
687687
if is_scalar(left) and isna(left):
688688
return self._fill_value
689689
return Interval(left, right, inclusive=self.inclusive)
690-
# error: Argument 1 to "ndim" has incompatible type
691-
# "Union[ndarray[Any, Any], ExtensionArray]"; expected
692-
# "Union[Sequence[Sequence[Sequence[Sequence[Sequence[Any]]]]],
693-
# Union[Union[_SupportsArray[dtype[Any]],
694-
# Sequence[_SupportsArray[dtype[Any]]],
695-
# Sequence[Sequence[_SupportsArray[dtype[Any]]]],
696-
# Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]],
697-
# Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[Any]]]]]]],
698-
# Union[bool, int, float, complex, str, bytes,
699-
# Sequence[Union[bool, int, float, complex, str, bytes]],
700-
# Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]],
701-
# Sequence[Sequence[Sequence[Union[bool, int, float, complex, str, bytes]]]],
702-
# Sequence[Sequence[Sequence[Sequence[Union[bool, int, float,
703-
# complex, str, bytes]]]]]]]]"
704-
if np.ndim(left) > 1: # type: ignore[arg-type]
690+
if np.ndim(left) > 1:
705691
# GH#30588 multi-dimensional indexer disallowed
706692
raise ValueError("multi-dimensional indexing not allowed")
707693
return self._shallow_copy(left, right)
@@ -1679,7 +1665,14 @@ def isin(self, values) -> np.ndarray:
16791665
# complex128 ndarray is much more performant.
16801666
left = self._combined.view("complex128")
16811667
right = values._combined.view("complex128")
1682-
return np.in1d(left, right)
1668+
# error: Argument 1 to "in1d" has incompatible type
1669+
# "Union[ExtensionArray, ndarray[Any, Any],
1670+
# ndarray[Any, dtype[Any]]]"; expected
1671+
# "Union[_SupportsArray[dtype[Any]],
1672+
# _NestedSequence[_SupportsArray[dtype[Any]]], bool,
1673+
# int, float, complex, str, bytes, _NestedSequence[
1674+
# Union[bool, int, float, complex, str, bytes]]]"
1675+
return np.in1d(left, right) # type: ignore[arg-type]
16831676

16841677
elif needs_i8_conversion(self.left.dtype) ^ needs_i8_conversion(
16851678
values.left.dtype

pandas/core/arrays/masked.py

+13-9
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,7 @@ def __init__(
110110
self, values: np.ndarray, mask: npt.NDArray[np.bool_], copy: bool = False
111111
) -> None:
112112
# values is supposed to already be validated in the subclass
113-
if not (
114-
isinstance(mask, np.ndarray)
115-
and
116-
# error: Non-overlapping equality check
117-
# (left operand type: "dtype[bool_]", right operand type: "Type[bool_]")
118-
mask.dtype == np.bool_ # type: ignore[comparison-overlap]
119-
):
113+
if not (isinstance(mask, np.ndarray) and mask.dtype == np.bool_):
120114
raise TypeError(
121115
"mask should be boolean numpy array. Use "
122116
"the 'pd.array' function instead"
@@ -1157,7 +1151,12 @@ def any(self, *, skipna: bool = True, **kwargs):
11571151
nv.validate_any((), kwargs)
11581152

11591153
values = self._data.copy()
1160-
np.putmask(values, self._mask, self._falsey_value)
1154+
# error: Argument 3 to "putmask" has incompatible type "object";
1155+
# expected "Union[_SupportsArray[dtype[Any]],
1156+
# _NestedSequence[_SupportsArray[dtype[Any]]],
1157+
# bool, int, float, complex, str, bytes,
1158+
# _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"
1159+
np.putmask(values, self._mask, self._falsey_value) # type: ignore[arg-type]
11611160
result = values.any()
11621161
if skipna:
11631162
return result
@@ -1233,7 +1232,12 @@ def all(self, *, skipna: bool = True, **kwargs):
12331232
nv.validate_all((), kwargs)
12341233

12351234
values = self._data.copy()
1236-
np.putmask(values, self._mask, self._truthy_value)
1235+
# error: Argument 3 to "putmask" has incompatible type "object";
1236+
# expected "Union[_SupportsArray[dtype[Any]],
1237+
# _NestedSequence[_SupportsArray[dtype[Any]]],
1238+
# bool, int, float, complex, str, bytes,
1239+
# _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"
1240+
np.putmask(values, self._mask, self._truthy_value) # type: ignore[arg-type]
12371241
result = values.all()
12381242

12391243
if skipna:

pandas/core/arrays/sparse/array.py

+16-3
Original file line numberDiff line numberDiff line change
@@ -944,7 +944,16 @@ def __getitem__(
944944
if is_integer(key):
945945
return self._get_val_at(key)
946946
elif isinstance(key, tuple):
947-
data_slice = self.to_dense()[key]
947+
# error: Invalid index type "Tuple[Union[int, ellipsis], ...]"
948+
# for "ndarray[Any, Any]"; expected type
949+
# "Union[SupportsIndex, _SupportsArray[dtype[Union[bool_,
950+
# integer[Any]]]], _NestedSequence[_SupportsArray[dtype[
951+
# Union[bool_, integer[Any]]]]], _NestedSequence[Union[
952+
# bool, int]], Tuple[Union[SupportsIndex, _SupportsArray[
953+
# dtype[Union[bool_, integer[Any]]]], _NestedSequence[
954+
# _SupportsArray[dtype[Union[bool_, integer[Any]]]]],
955+
# _NestedSequence[Union[bool, int]]], ...]]"
956+
data_slice = self.to_dense()[key] # type: ignore[index]
948957
elif isinstance(key, slice):
949958

950959
# Avoid densifying when handling contiguous slices
@@ -1184,7 +1193,10 @@ def _concat_same_type(
11841193

11851194
data = np.concatenate(values)
11861195
indices_arr = np.concatenate(indices)
1187-
sp_index = IntIndex(length, indices_arr)
1196+
# error: Argument 2 to "IntIndex" has incompatible type
1197+
# "ndarray[Any, dtype[signedinteger[_32Bit]]]";
1198+
# expected "Sequence[int]"
1199+
sp_index = IntIndex(length, indices_arr) # type: ignore[arg-type]
11881200

11891201
else:
11901202
# when concatenating block indices, we don't claim that you'll
@@ -1374,7 +1386,8 @@ def __setstate__(self, state):
13741386
if isinstance(state, tuple):
13751387
# Compat for pandas < 0.24.0
13761388
nd_state, (fill_value, sp_index) = state
1377-
sparse_values = np.array([])
1389+
# error: Need type annotation for "sparse_values"
1390+
sparse_values = np.array([]) # type: ignore[var-annotated]
13781391
sparse_values.__setstate__(nd_state)
13791392

13801393
self._sparse_values = sparse_values

pandas/core/dtypes/astype.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -113,9 +113,7 @@ def astype_nansafe(
113113
).reshape(shape)
114114

115115
elif is_datetime64_dtype(arr.dtype):
116-
# error: Non-overlapping equality check (left
117-
# operand type: "dtype[Any]", right operand type: "Type[signedinteger[Any]]")
118-
if dtype == np.int64: # type: ignore[comparison-overlap]
116+
if dtype == np.int64:
119117
if isna(arr).any():
120118
raise ValueError("Cannot convert NaT values to integer")
121119
return arr.view(dtype)
@@ -127,9 +125,7 @@ def astype_nansafe(
127125
raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]")
128126

129127
elif is_timedelta64_dtype(arr.dtype):
130-
# error: Non-overlapping equality check (left
131-
# operand type: "dtype[Any]", right operand type: "Type[signedinteger[Any]]")
132-
if dtype == np.int64: # type: ignore[comparison-overlap]
128+
if dtype == np.int64:
133129
if isna(arr).any():
134130
raise ValueError("Cannot convert NaT values to integer")
135131
return arr.view(dtype)

pandas/core/dtypes/common.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -534,9 +534,7 @@ def is_string_or_object_np_dtype(dtype: np.dtype) -> bool:
534534
"""
535535
Faster alternative to is_string_dtype, assumes we have a np.dtype object.
536536
"""
537-
# error: Non-overlapping equality check (left operand type:
538-
# "dtype[Any]", right operand type: "Type[object]")
539-
return dtype == object or dtype.kind in "SU" # type: ignore[comparison-overlap]
537+
return dtype == object or dtype.kind in "SU"
540538

541539

542540
def is_string_dtype(arr_or_dtype) -> bool:

pandas/core/exchange/buffer.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,7 @@ def __dlpack__(self):
5757
Represent this structure as DLPack interface.
5858
"""
5959
if _NUMPY_HAS_DLPACK:
60-
# error: "ndarray[Any, Any]" has no attribute "__dlpack__"
61-
return self._x.__dlpack__() # type: ignore[attr-defined]
60+
return self._x.__dlpack__()
6261
raise NotImplementedError("__dlpack__")
6362

6463
def __dlpack_device__(self) -> Tuple[DlpackDeviceType, Optional[int]]:

pandas/core/frame.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2481,7 +2481,9 @@ def to_records(
24812481
if dtype_mapping is None:
24822482
formats.append(v.dtype)
24832483
elif isinstance(dtype_mapping, (type, np.dtype, str)):
2484-
formats.append(dtype_mapping)
2484+
# error: Argument 1 to "append" of "list" has incompatible
2485+
# type "Union[type, dtype[Any], str]"; expected "dtype[Any]"
2486+
formats.append(dtype_mapping) # type: ignore[arg-type]
24852487
else:
24862488
element = "row" if i < index_len else "column"
24872489
msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}"

pandas/core/indexes/base.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -4834,7 +4834,13 @@ def _join_non_unique(
48344834
right = other._values.take(right_idx)
48354835

48364836
if isinstance(join_array, np.ndarray):
4837-
np.putmask(join_array, mask, right)
4837+
# error: Argument 3 to "putmask" has incompatible type
4838+
# "Union[ExtensionArray, ndarray[Any, Any]]"; expected
4839+
# "Union[_SupportsArray[dtype[Any]], _NestedSequence[
4840+
# _SupportsArray[dtype[Any]]], bool, int, float, complex,
4841+
# str, bytes, _NestedSequence[Union[bool, int, float,
4842+
# complex, str, bytes]]]"
4843+
np.putmask(join_array, mask, right) # type: ignore[arg-type]
48384844
else:
48394845
join_array._putmask(mask, right)
48404846

@@ -5348,7 +5354,10 @@ def __getitem__(self, key):
53485354
if hasattr(result, "_ndarray"):
53495355
# i.e. NDArrayBackedExtensionArray
53505356
# Unpack to ndarray for MPL compat
5351-
return result._ndarray
5357+
# error: Item "ndarray[Any, Any]" of
5358+
# "Union[ExtensionArray, ndarray[Any, Any]]"
5359+
# has no attribute "_ndarray"
5360+
return result._ndarray # type: ignore[union-attr]
53525361
return result
53535362

53545363
# NB: Using _constructor._simple_new would break if MultiIndex
@@ -6886,7 +6895,9 @@ def insert(self, loc: int, item) -> Index:
68866895
new_values = np.insert(arr, loc, casted)
68876896

68886897
else:
6889-
new_values = np.insert(arr, loc, None)
6898+
# error: No overload variant of "insert" matches argument types
6899+
# "ndarray[Any, Any]", "int", "None"
6900+
new_values = np.insert(arr, loc, None) # type: ignore[call-overload]
68906901
loc = loc if loc >= 0 else loc - 1
68916902
new_values[loc] = item
68926903

pandas/core/indexes/multi.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,10 @@ def _validate_codes(self, level: list, code: list):
363363
"""
364364
null_mask = isna(level)
365365
if np.any(null_mask):
366-
code = np.where(null_mask[code], -1, code)
366+
# error: Incompatible types in assignment
367+
# (expression has type "ndarray[Any, dtype[Any]]",
368+
# variable has type "List[Any]")
369+
code = np.where(null_mask[code], -1, code) # type: ignore[assignment]
367370
return code
368371

369372
def _verify_integrity(self, codes: list | None = None, levels: list | None = None):
@@ -1577,7 +1580,13 @@ def is_monotonic_increasing(self) -> bool:
15771580
self._get_level_values(i)._values for i in reversed(range(len(self.levels)))
15781581
]
15791582
try:
1580-
sort_order = np.lexsort(values)
1583+
# error: Argument 1 to "lexsort" has incompatible type
1584+
# "List[Union[ExtensionArray, ndarray[Any, Any]]]";
1585+
# expected "Union[_SupportsArray[dtype[Any]],
1586+
# _NestedSequence[_SupportsArray[dtype[Any]]], bool,
1587+
# int, float, complex, str, bytes, _NestedSequence[Union
1588+
# [bool, int, float, complex, str, bytes]]]"
1589+
sort_order = np.lexsort(values) # type: ignore[arg-type]
15811590
return Index(sort_order).is_monotonic_increasing
15821591
except TypeError:
15831592

pandas/core/internals/ops.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -125,9 +125,7 @@ def _get_same_shape_values(
125125
# argument type "Tuple[Union[ndarray, slice], slice]"
126126
lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[call-overload]
127127
assert lvals.shape[0] == 1, lvals.shape
128-
# error: No overload variant of "__getitem__" of "ExtensionArray" matches
129-
# argument type "Tuple[int, slice]"
130-
lvals = lvals[0, :] # type: ignore[call-overload]
128+
lvals = lvals[0, :]
131129
else:
132130
# lvals are 1D, rvals are 2D
133131
assert rvals.shape[0] == 1, rvals.shape

pandas/core/missing.py

+19-3
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,13 @@ def func(yvalues: np.ndarray) -> None:
333333
**kwargs,
334334
)
335335

336-
np.apply_along_axis(func, axis, data)
336+
# error: Argument 1 to "apply_along_axis" has incompatible type
337+
# "Callable[[ndarray[Any, Any]], None]"; expected "Callable[...,
338+
# Union[_SupportsArray[dtype[<nothing>]], Sequence[_SupportsArray
339+
# [dtype[<nothing>]]], Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]],
340+
# Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]],
341+
# Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]]]]]"
342+
np.apply_along_axis(func, axis, data) # type: ignore[arg-type]
337343
return
338344

339345

@@ -772,13 +778,23 @@ def interpolate_2d(
772778
"""
773779
if limit_area is not None:
774780
np.apply_along_axis(
775-
partial(
781+
# error: Argument 1 to "apply_along_axis" has incompatible type
782+
# "partial[None]"; expected
783+
# "Callable[..., Union[_SupportsArray[dtype[<nothing>]],
784+
# Sequence[_SupportsArray[dtype[<nothing>]]],
785+
# Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]],
786+
# Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]],
787+
# Sequence[Sequence[Sequence[Sequence[_
788+
# SupportsArray[dtype[<nothing>]]]]]]]]"
789+
partial( # type: ignore[arg-type]
776790
_interpolate_with_limit_area,
777791
method=method,
778792
limit=limit,
779793
limit_area=limit_area,
780794
),
781-
axis,
795+
# error: Argument 2 to "apply_along_axis" has incompatible type
796+
# "Union[str, int]"; expected "SupportsIndex"
797+
axis, # type: ignore[arg-type]
782798
values,
783799
)
784800
return

pandas/core/reshape/melt.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,9 @@ def melt(
133133
if is_extension_array_dtype(id_data):
134134
id_data = concat([id_data] * K, ignore_index=True)
135135
else:
136-
id_data = np.tile(id_data._values, K)
136+
# error: Incompatible types in assignment (expression has type
137+
# "ndarray[Any, dtype[Any]]", variable has type "Series")
138+
id_data = np.tile(id_data._values, K) # type: ignore[assignment]
137139
mdata[col] = id_data
138140

139141
mcolumns = id_vars + var_name + [value_name]

pandas/core/series.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -2024,7 +2024,9 @@ def count(self, level=None):
20242024
lev = lev.insert(cnt, lev._na_value)
20252025

20262026
obs = level_codes[notna(self._values)]
2027-
out = np.bincount(obs, minlength=len(lev) or None)
2027+
# error: Argument "minlength" to "bincount" has incompatible type
2028+
# "Optional[int]"; expected "SupportsIndex"
2029+
out = np.bincount(obs, minlength=len(lev) or None) # type: ignore[arg-type]
20282030
return self._constructor(out, index=lev, dtype="int64").__finalize__(
20292031
self, method="count"
20302032
)

0 commit comments

Comments
 (0)