Skip to content

Commit adec21f

Browse files
authored
TYP: Add ignores for numpy 2.2 updates (#61265)
* TYP: Add ignores for numpy 2.2 updates * fix tests and plotting * ignore pyright error
1 parent 4b8c472 commit adec21f

28 files changed

+43
-63
lines changed

pandas/core/algorithms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ def _reconstruct_data(
215215
values = cls._from_sequence(values, dtype=dtype) # type: ignore[assignment]
216216

217217
else:
218-
values = values.astype(dtype, copy=False)
218+
values = values.astype(dtype, copy=False) # type: ignore[assignment]
219219

220220
return values
221221

pandas/core/array_algos/quantile.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def quantile_with_mask(
102102
interpolation=interpolation,
103103
)
104104

105-
result = np.asarray(result)
105+
result = np.asarray(result) # type: ignore[assignment]
106106
result = result.T
107107

108108
return result
@@ -196,7 +196,7 @@ def _nanquantile(
196196
# Caller is responsible for ensuring mask shape match
197197
assert mask.shape == values.shape
198198
result = [
199-
_nanquantile_1d(val, m, qs, na_value, interpolation=interpolation)
199+
_nanquantile_1d(val, m, qs, na_value, interpolation=interpolation) # type: ignore[arg-type]
200200
for (val, m) in zip(list(values), list(mask))
201201
]
202202
if values.dtype.kind == "f":

pandas/core/arrays/_mixins.py

+1-7
Original file line numberDiff line numberDiff line change
@@ -142,18 +142,12 @@ def view(self, dtype: Dtype | None = None) -> ArrayLike:
142142

143143
dt64_values = arr.view(dtype)
144144
return DatetimeArray._simple_new(dt64_values, dtype=dtype)
145-
146145
elif lib.is_np_dtype(dtype, "m") and is_supported_dtype(dtype):
147146
from pandas.core.arrays import TimedeltaArray
148147

149148
td64_values = arr.view(dtype)
150149
return TimedeltaArray._simple_new(td64_values, dtype=dtype)
151-
152-
# error: Argument "dtype" to "view" of "_ArrayOrScalarCommon" has incompatible
153-
# type "Union[ExtensionDtype, dtype[Any]]"; expected "Union[dtype[Any], None,
154-
# type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int,
155-
# Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]"
156-
return arr.view(dtype=dtype) # type: ignore[arg-type]
150+
return arr.view(dtype=dtype)
157151

158152
def take(
159153
self,

pandas/core/arrays/arrow/_arrow_utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def pyarrow_array_to_numpy_and_mask(
4444
mask = pyarrow.BooleanArray.from_buffers(
4545
pyarrow.bool_(), len(arr), [None, bitmask], offset=arr.offset
4646
)
47-
mask = np.asarray(mask)
47+
mask = np.asarray(mask) # type: ignore[assignment]
4848
else:
4949
mask = np.ones(len(arr), dtype=bool)
5050
return data, mask

pandas/core/arrays/arrow/array.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2540,7 +2540,7 @@ def _str_get_dummies(self, sep: str = "|", dtype: NpDtype | None = None):
25402540
dummies_dtype = np.bool_
25412541
dummies = np.zeros(n_rows * n_cols, dtype=dummies_dtype)
25422542
dummies[indices] = True
2543-
dummies = dummies.reshape((n_rows, n_cols))
2543+
dummies = dummies.reshape((n_rows, n_cols)) # type: ignore[assignment]
25442544
result = type(self)(pa.array(list(dummies)))
25452545
return result, uniques_sorted.to_pylist()
25462546

pandas/core/arrays/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -596,7 +596,7 @@ def to_numpy(
596596
if copy or na_value is not lib.no_default:
597597
result = result.copy()
598598
if na_value is not lib.no_default:
599-
result[self.isna()] = na_value
599+
result[self.isna()] = na_value # type: ignore[index]
600600
return result
601601

602602
# ------------------------------------------------------------------------

pandas/core/arrays/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1853,7 +1853,7 @@ def value_counts(self, dropna: bool = True) -> Series:
18531853
count = np.bincount(obs, minlength=ncat or 0)
18541854
else:
18551855
count = np.bincount(np.where(mask, code, ncat))
1856-
ix = np.append(ix, -1)
1856+
ix = np.append(ix, -1) # type: ignore[assignment]
18571857

18581858
ix = coerce_indexer_dtype(ix, self.dtype.categories)
18591859
ix_categorical = self._from_backing_data(ix)

pandas/core/arrays/datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2394,7 +2394,7 @@ def take(
23942394
)
23952395

23962396
indices = np.asarray(indices, dtype=np.intp)
2397-
maybe_slice = lib.maybe_indices_to_slice(indices, len(self))
2397+
maybe_slice = lib.maybe_indices_to_slice(indices, len(self)) # type: ignore[arg-type]
23982398

23992399
if isinstance(maybe_slice, slice):
24002400
freq = self._get_getitem_freq(maybe_slice)

pandas/core/arrays/datetimes.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ def _simple_new( # type: ignore[override]
331331
else:
332332
# DatetimeTZDtype. If we have e.g. DatetimeTZDtype[us, UTC],
333333
# then values.dtype should be M8[us].
334-
assert dtype._creso == get_unit_from_dtype(values.dtype)
334+
assert dtype._creso == get_unit_from_dtype(values.dtype) # type: ignore[union-attr]
335335

336336
result = super()._simple_new(values, dtype)
337337
result._freq = freq
@@ -542,7 +542,7 @@ def _unbox_scalar(self, value) -> np.datetime64:
542542
raise ValueError("'value' should be a Timestamp.")
543543
self._check_compatible_with(value)
544544
if value is NaT:
545-
return np.datetime64(value._value, self.unit)
545+
return np.datetime64(value._value, self.unit) # type: ignore[call-overload]
546546
else:
547547
return value.as_unit(self.unit, round_ok=False).asm8
548548

@@ -813,10 +813,7 @@ def _add_offset(self, offset: BaseOffset) -> Self:
813813
try:
814814
res_values = offset._apply_array(values._ndarray)
815815
if res_values.dtype.kind == "i":
816-
# error: Argument 1 to "view" of "ndarray" has incompatible type
817-
# "dtype[datetime64] | DatetimeTZDtype"; expected
818-
# "dtype[Any] | type[Any] | _SupportsDType[dtype[Any]]"
819-
res_values = res_values.view(values.dtype) # type: ignore[arg-type]
816+
res_values = res_values.view(values.dtype)
820817
except NotImplementedError:
821818
if get_option("performance_warnings"):
822819
warnings.warn(

pandas/core/arrays/masked.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -515,7 +515,7 @@ def tolist(self) -> list:
515515
if self.ndim > 1:
516516
return [x.tolist() for x in self]
517517
dtype = None if self._hasna else self._data.dtype
518-
return self.to_numpy(dtype=dtype, na_value=libmissing.NA).tolist()
518+
return self.to_numpy(dtype=dtype, na_value=libmissing.NA).tolist() # type: ignore[return-value]
519519

520520
@overload
521521
def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray: ...
@@ -1497,10 +1497,10 @@ def all(
14971497
result = values.all(axis=axis)
14981498

14991499
if skipna:
1500-
return result
1500+
return result # type: ignore[return-value]
15011501
else:
15021502
if not result or len(self) == 0 or not self._mask.any():
1503-
return result
1503+
return result # type: ignore[return-value]
15041504
else:
15051505
return self.dtype.na_value
15061506

pandas/core/arrays/sparse/scipy_sparse.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def _levels_to_axis(
7979
ax_coords = codes[valid_ilocs]
8080

8181
ax_labels = ax_labels.tolist()
82-
return ax_coords, ax_labels
82+
return ax_coords, ax_labels # pyright: ignore[reportReturnType]
8383

8484

8585
def _to_ijv(

pandas/core/arrays/timedeltas.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ def _unbox_scalar(self, value) -> np.timedelta64:
325325
raise ValueError("'value' should be a Timedelta.")
326326
self._check_compatible_with(value)
327327
if value is NaT:
328-
return np.timedelta64(value._value, self.unit)
328+
return np.timedelta64(value._value, self.unit) # type: ignore[call-overload]
329329
else:
330330
return value.as_unit(self.unit, round_ok=False).asm8
331331

pandas/core/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -875,7 +875,7 @@ def tolist(self) -> list:
875875
>>> idx.to_list()
876876
[1, 2, 3]
877877
"""
878-
return self._values.tolist()
878+
return self._values.tolist() # type: ignore[return-value]
879879

880880
to_list = tolist
881881

pandas/core/groupby/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2142,7 +2142,7 @@ def _wrap_applied_output_series(
21422142

21432143
if stacked_values.dtype == object:
21442144
# We'll have the DataFrame constructor do inference
2145-
stacked_values = stacked_values.tolist()
2145+
stacked_values = stacked_values.tolist() # type: ignore[assignment]
21462146
result = self.obj._constructor(stacked_values, index=index, columns=columns)
21472147

21482148
if not self.as_index:

pandas/core/groupby/groupby.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1878,7 +1878,7 @@ def _apply_filter(self, indices, dropna):
18781878
mask.fill(False)
18791879
mask[indices.astype(int)] = True
18801880
# mask fails to broadcast when passed to where; broadcast manually.
1881-
mask = np.tile(mask, list(self._selected_obj.shape[1:]) + [1]).T
1881+
mask = np.tile(mask, list(self._selected_obj.shape[1:]) + [1]).T # type: ignore[assignment]
18821882
filtered = self._selected_obj.where(mask) # Fill with NaNs.
18831883
return filtered
18841884

@@ -4441,11 +4441,11 @@ def blk_func(values: ArrayLike) -> ArrayLike:
44414441
)
44424442

44434443
if vals.ndim == 1:
4444-
out = out.ravel("K")
4444+
out = out.ravel("K") # type: ignore[assignment]
44454445
if result_mask is not None:
4446-
result_mask = result_mask.ravel("K")
4446+
result_mask = result_mask.ravel("K") # type: ignore[assignment]
44474447
else:
4448-
out = out.reshape(ncols, ngroups * nqs)
4448+
out = out.reshape(ncols, ngroups * nqs) # type: ignore[assignment]
44494449

44504450
return post_processor(out, inference, result_mask, orig_vals)
44514451

pandas/core/groupby/ops.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1131,7 +1131,7 @@ def get_iterator(self, data: NDFrame):
11311131
"""
11321132
slicer = lambda start, edge: data.iloc[start:edge]
11331133

1134-
start = 0
1134+
start: np.int64 | int = 0
11351135
for edge, label in zip(self.bins, self.binlabels):
11361136
if label is not NaT:
11371137
yield label, slicer(start, edge)
@@ -1144,7 +1144,7 @@ def get_iterator(self, data: NDFrame):
11441144
def indices(self):
11451145
indices = collections.defaultdict(list)
11461146

1147-
i = 0
1147+
i: np.int64 | int = 0
11481148
for label, bin in zip(self.binlabels, self.bins):
11491149
if i < bin:
11501150
if label is not NaT:

pandas/core/indexers/objects.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,8 @@ def get_window_bounds(
131131
if closed in ["left", "neither"]:
132132
end -= 1
133133

134-
end = np.clip(end, 0, num_values)
135-
start = np.clip(start, 0, num_values)
134+
end = np.clip(end, 0, num_values) # type: ignore[assignment]
135+
start = np.clip(start, 0, num_values) # type: ignore[assignment]
136136

137137
return start, end
138138

@@ -402,7 +402,7 @@ def get_window_bounds(
402402
start = np.arange(0, num_values, step, dtype="int64")
403403
end = start + self.window_size
404404
if self.window_size:
405-
end = np.clip(end, 0, num_values)
405+
end = np.clip(end, 0, num_values) # type: ignore[assignment]
406406

407407
return start, end
408408

@@ -488,7 +488,7 @@ def get_window_bounds(
488488
)
489489
window_indices_start += len(indices)
490490
# Extend as we'll be slicing window like [start, end)
491-
window_indices = np.append(window_indices, [window_indices[-1] + 1]).astype(
491+
window_indices = np.append(window_indices, [window_indices[-1] + 1]).astype( # type: ignore[assignment]
492492
np.int64, copy=False
493493
)
494494
start_arrays.append(window_indices.take(ensure_platform_int(start)))

pandas/core/indexes/interval.py

+1-8
Original file line numberDiff line numberDiff line change
@@ -1279,14 +1279,7 @@ def interval_range(
12791279
breaks = np.linspace(start, end, periods)
12801280
if all(is_integer(x) for x in com.not_none(start, end, freq)):
12811281
# np.linspace always produces float output
1282-
1283-
# error: Argument 1 to "maybe_downcast_numeric" has incompatible type
1284-
# "Union[ndarray[Any, Any], TimedeltaIndex, DatetimeIndex]";
1285-
# expected "ndarray[Any, Any]" [
1286-
breaks = maybe_downcast_numeric(
1287-
breaks, # type: ignore[arg-type]
1288-
dtype,
1289-
)
1282+
breaks = maybe_downcast_numeric(breaks, dtype)
12901283
else:
12911284
# delegate to the appropriate range function
12921285
if isinstance(endpoint, Timestamp):

pandas/core/internals/blocks.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2094,7 +2094,7 @@ def _unstack(
20942094
self.values.take(
20952095
indices, allow_fill=needs_masking[i], fill_value=fill_value
20962096
),
2097-
BlockPlacement(place),
2097+
BlockPlacement(place), # type: ignore[arg-type]
20982098
ndim=2,
20992099
)
21002100
for i, (indices, place) in enumerate(zip(new_values, new_placement))

pandas/core/internals/construction.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,7 @@ def reorder_arrays(
634634
arr = np.empty(length, dtype=object)
635635
arr.fill(np.nan)
636636
else:
637-
arr = arrays[k]
637+
arr = arrays[k] # type: ignore[assignment]
638638
new_arrays.append(arr)
639639

640640
arrays = new_arrays

pandas/core/missing.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,8 @@ def find_valid_index(how: str, is_valid: npt.NDArray[np.bool_]) -> int | None:
241241
return None
242242

243243
if is_valid.ndim == 2:
244-
is_valid = is_valid.any(axis=1) # reduce axis 1
244+
# reduce axis 1
245+
is_valid = is_valid.any(axis=1) # type: ignore[assignment]
245246

246247
if how == "first":
247248
idxpos = is_valid[::].argmax()
@@ -404,10 +405,7 @@ def func(yvalues: np.ndarray) -> None:
404405
**kwargs,
405406
)
406407

407-
# error: No overload variant of "apply_along_axis" matches
408-
# argument types "Callable[[ndarray[Any, Any]], None]",
409-
# "int", "ndarray[Any, Any]"
410-
np.apply_along_axis(func, axis, data) # type: ignore[call-overload]
408+
np.apply_along_axis(func, axis, data)
411409

412410

413411
def _index_to_interp_indices(index: Index, method: str) -> np.ndarray:

pandas/core/reshape/encoding.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ def get_empty_frame(data) -> DataFrame:
357357

358358
if drop_first:
359359
# remove first GH12042
360-
dummy_mat = dummy_mat[:, 1:]
360+
dummy_mat = dummy_mat[:, 1:] # type: ignore[assignment]
361361
dummy_cols = dummy_cols[1:]
362362
return DataFrame(dummy_mat, index=index, columns=dummy_cols, dtype=_dtype)
363363

pandas/core/reshape/merge.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -2921,9 +2921,7 @@ def _convert_arrays_and_get_rizer_klass(
29212921
lk = lk.astype(dtype, copy=False)
29222922
rk = rk.astype(dtype, copy=False)
29232923
if isinstance(lk, BaseMaskedArray):
2924-
# Invalid index type "type" for "Dict[Type[object], Type[Factorizer]]";
2925-
# expected type "Type[object]"
2926-
klass = _factorizers[lk.dtype.type] # type: ignore[index]
2924+
klass = _factorizers[lk.dtype.type]
29272925
elif isinstance(lk.dtype, ArrowDtype):
29282926
klass = _factorizers[lk.dtype.numpy_dtype.type]
29292927
else:

pandas/core/sorting.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ def nargminmax(values: ExtensionArray, method: str, axis: AxisInt = 0):
476476
zipped = zip(arr_values, mask)
477477
else:
478478
zipped = zip(arr_values.T, mask.T)
479-
return np.array([_nanargminmax(v, m, func) for v, m in zipped])
479+
return np.array([_nanargminmax(v, m, func) for v, m in zipped]) # type: ignore[arg-type]
480480
return func(arr_values, axis=axis)
481481

482482
return _nanargminmax(arr_values, mask, func)

pandas/io/formats/format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1495,7 +1495,7 @@ def _format_strings(self) -> list[str]:
14951495
fmt_values = values._format_native_types(
14961496
na_rep=self.nat_rep, date_format=self.date_format
14971497
)
1498-
return fmt_values.tolist()
1498+
return fmt_values.tolist() # type: ignore[return-value]
14991499

15001500

15011501
class _ExtensionArrayFormatter(_GenericArrayFormatter):

pandas/io/parsers/python_parser.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1468,7 +1468,7 @@ def detect_colspecs(
14681468
shifted[0] = 0
14691469
edges = np.where((mask ^ shifted) == 1)[0]
14701470
edge_pairs = list(zip(edges[::2], edges[1::2]))
1471-
return edge_pairs
1471+
return edge_pairs # type: ignore[return-value]
14721472

14731473
def __next__(self) -> list[str]:
14741474
# Argument 1 to "next" has incompatible type "Union[IO[str],

pandas/plotting/_matplotlib/style.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ def _random_color(column: int) -> list[float]:
273273
"""Get a random color represented as a list of length 3"""
274274
# GH17525 use common._random_state to avoid resetting the seed
275275
rs = com.random_state(column)
276-
return rs.rand(3).tolist()
276+
return rs.rand(3).tolist() # type: ignore[return-value]
277277

278278

279279
def _is_single_string_color(color: Color) -> bool:

pandas/tests/dtypes/test_missing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -769,8 +769,8 @@ def test_empty_like(self):
769769
np.datetime64("NaT"),
770770
np.timedelta64("NaT"),
771771
]
772-
+ [np.datetime64("NaT", unit) for unit in m8_units]
773-
+ [np.timedelta64("NaT", unit) for unit in m8_units]
772+
+ [np.datetime64("NaT", unit) for unit in m8_units] # type: ignore[call-overload]
773+
+ [np.timedelta64("NaT", unit) for unit in m8_units] # type: ignore[call-overload]
774774
)
775775

776776
inf_vals = [

0 commit comments

Comments
 (0)