Skip to content

Commit d02aea9

Browse files
committed
Backport PR #61265: TYP: Add ignores for numpy 2.2 updates
1 parent 9bb152d commit d02aea9

27 files changed

+42
-65
lines changed

pandas/core/algorithms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ def _reconstruct_data(
209209
values = cls._from_sequence(values, dtype=dtype)
210210

211211
else:
212-
values = values.astype(dtype, copy=False)
212+
values = values.astype(dtype, copy=False) # type: ignore[assignment]
213213

214214
return values
215215

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 _nanpercentile(
196196
# Caller is responsible for ensuring mask shape match
197197
assert mask.shape == values.shape
198198
result = [
199-
_nanpercentile_1d(val, m, qs, na_value, interpolation=interpolation)
199+
_nanpercentile_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
@@ -141,18 +141,12 @@ def view(self, dtype: Dtype | None = None) -> ArrayLike:
141141

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

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

157151
def take(
158152
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
@@ -2499,7 +2499,7 @@ def _str_get_dummies(self, sep: str = "|"):
24992499
indices = indices + np.arange(n_rows).repeat(lengths) * n_cols
25002500
dummies = np.zeros(n_rows * n_cols, dtype=np.bool_)
25012501
dummies[indices] = True
2502-
dummies = dummies.reshape((n_rows, n_cols))
2502+
dummies = dummies.reshape((n_rows, n_cols)) # type: ignore[assignment]
25032503
result = type(self)(pa.array(list(dummies)))
25042504
return result, uniques_sorted.to_pylist()
25052505

pandas/core/arrays/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ def to_numpy(
569569
if copy or na_value is not lib.no_default:
570570
result = result.copy()
571571
if na_value is not lib.no_default:
572-
result[self.isna()] = na_value
572+
result[self.isna()] = na_value # type: ignore[index]
573573
return result
574574

575575
# ------------------------------------------------------------------------

pandas/core/arrays/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1839,7 +1839,7 @@ def value_counts(self, dropna: bool = True) -> Series:
18391839
count = np.bincount(obs, minlength=ncat or 0)
18401840
else:
18411841
count = np.bincount(np.where(mask, code, ncat))
1842-
ix = np.append(ix, -1)
1842+
ix = np.append(ix, -1) # type: ignore[assignment]
18431843

18441844
ix = coerce_indexer_dtype(ix, self.dtype.categories)
18451845
ix = self._from_backing_data(ix)

pandas/core/arrays/datetimes.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def _simple_new( # type: ignore[override]
318318
else:
319319
# DatetimeTZDtype. If we have e.g. DatetimeTZDtype[us, UTC],
320320
# then values.dtype should be M8[us].
321-
assert dtype._creso == get_unit_from_dtype(values.dtype)
321+
assert dtype._creso == get_unit_from_dtype(values.dtype) # type: ignore[union-attr]
322322

323323
result = super()._simple_new(values, dtype)
324324
result._freq = freq
@@ -529,7 +529,7 @@ def _unbox_scalar(self, value) -> np.datetime64:
529529
raise ValueError("'value' should be a Timestamp.")
530530
self._check_compatible_with(value)
531531
if value is NaT:
532-
return np.datetime64(value._value, self.unit)
532+
return np.datetime64(value._value, self.unit) # type: ignore[call-overload]
533533
else:
534534
return value.as_unit(self.unit).asm8
535535

@@ -803,10 +803,7 @@ def _add_offset(self, offset: BaseOffset) -> Self:
803803
try:
804804
res_values = offset._apply_array(values._ndarray)
805805
if res_values.dtype.kind == "i":
806-
# error: Argument 1 to "view" of "ndarray" has incompatible type
807-
# "dtype[datetime64] | DatetimeTZDtype"; expected
808-
# "dtype[Any] | type[Any] | _SupportsDType[dtype[Any]]"
809-
res_values = res_values.view(values.dtype) # type: ignore[arg-type]
806+
res_values = res_values.view(values.dtype)
810807
except NotImplementedError:
811808
warnings.warn(
812809
"Non-vectorized DateOffset being applied to Series or DatetimeIndex.",

pandas/core/arrays/masked.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,7 @@ def tolist(self):
532532
if self.ndim > 1:
533533
return [x.tolist() for x in self]
534534
dtype = None if self._hasna else self._data.dtype
535-
return self.to_numpy(dtype=dtype, na_value=libmissing.NA).tolist()
535+
return self.to_numpy(dtype=dtype, na_value=libmissing.NA).tolist() # type: ignore[return-value]
536536

537537
@overload
538538
def astype(self, dtype: npt.DTypeLike, copy: bool = ...) -> np.ndarray:
@@ -1512,10 +1512,10 @@ def all(self, *, skipna: bool = True, axis: AxisInt | None = 0, **kwargs):
15121512
result = values.all(axis=axis)
15131513

15141514
if skipna:
1515-
return result
1515+
return result # type: ignore[return-value]
15161516
else:
15171517
if not result or len(self) == 0 or not self._mask.any():
1518-
return result
1518+
return result # type: ignore[return-value]
15191519
else:
15201520
return self.dtype.na_value
15211521

pandas/core/arrays/sparse/scipy_sparse.py

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

8080
ax_labels = ax_labels.tolist()
81-
return ax_coords, ax_labels
81+
return ax_coords, ax_labels # pyright: ignore[reportReturnType]
8282

8383

8484
def _to_ijv(

pandas/core/arrays/timedeltas.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ def _unbox_scalar(self, value) -> np.timedelta64:
321321
raise ValueError("'value' should be a Timedelta.")
322322
self._check_compatible_with(value)
323323
if value is NaT:
324-
return np.timedelta64(value._value, self.unit)
324+
return np.timedelta64(value._value, self.unit) # type: ignore[call-overload]
325325
else:
326326
return value.as_unit(self.unit).asm8
327327

pandas/core/base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -833,7 +833,7 @@ def tolist(self):
833833
>>> idx.to_list()
834834
[1, 2, 3]
835835
"""
836-
return self._values.tolist()
836+
return self._values.tolist() # type: ignore[return-value]
837837

838838
to_list = tolist
839839

pandas/core/groupby/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1666,7 +1666,7 @@ def _wrap_applied_output_series(
16661666

16671667
if stacked_values.dtype == object:
16681668
# We'll have the DataFrame constructor do inference
1669-
stacked_values = stacked_values.tolist()
1669+
stacked_values = stacked_values.tolist() # type: ignore[assignment]
16701670
result = self.obj._constructor(stacked_values, index=index, columns=columns)
16711671

16721672
if not self.as_index:

pandas/core/groupby/groupby.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -2095,7 +2095,7 @@ def _apply_filter(self, indices, dropna):
20952095
mask.fill(False)
20962096
mask[indices.astype(int)] = True
20972097
# mask fails to broadcast when passed to where; broadcast manually.
2098-
mask = np.tile(mask, list(self._selected_obj.shape[1:]) + [1]).T
2098+
mask = np.tile(mask, list(self._selected_obj.shape[1:]) + [1]).T # type: ignore[assignment]
20992099
filtered = self._selected_obj.where(mask) # Fill with NaNs.
21002100
return filtered
21012101

@@ -4549,11 +4549,11 @@ def blk_func(values: ArrayLike) -> ArrayLike:
45494549
)
45504550

45514551
if vals.ndim == 1:
4552-
out = out.ravel("K")
4552+
out = out.ravel("K") # type: ignore[assignment]
45534553
if result_mask is not None:
4554-
result_mask = result_mask.ravel("K")
4554+
result_mask = result_mask.ravel("K") # type: ignore[assignment]
45554555
else:
4556-
out = out.reshape(ncols, ngroups * nqs)
4556+
out = out.reshape(ncols, ngroups * nqs) # type: ignore[assignment]
45574557

45584558
return post_processor(out, inference, result_mask, orig_vals)
45594559

pandas/core/groupby/ops.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1040,7 +1040,7 @@ def get_iterator(self, data: NDFrame, axis: AxisInt = 0):
10401040

10411041
length = len(data.axes[axis])
10421042

1043-
start = 0
1043+
start: np.int64 | int = 0
10441044
for edge, label in zip(self.bins, self.binlabels):
10451045
if label is not NaT:
10461046
yield label, slicer(start, edge)
@@ -1053,7 +1053,7 @@ def get_iterator(self, data: NDFrame, axis: AxisInt = 0):
10531053
def indices(self):
10541054
indices = collections.defaultdict(list)
10551055

1056-
i = 0
1056+
i: np.int64 | int = 0
10571057
for label, bin in zip(self.binlabels, self.bins):
10581058
if i < bin:
10591059
if label is not NaT:

pandas/core/indexers/objects.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,8 @@ def get_window_bounds(
114114
if closed in ["left", "neither"]:
115115
end -= 1
116116

117-
end = np.clip(end, 0, num_values)
118-
start = np.clip(start, 0, num_values)
117+
end = np.clip(end, 0, num_values) # type: ignore[assignment]
118+
start = np.clip(start, 0, num_values) # type: ignore[assignment]
119119

120120
return start, end
121121

@@ -340,7 +340,7 @@ def get_window_bounds(
340340
start = np.arange(0, num_values, step, dtype="int64")
341341
end = start + self.window_size
342342
if self.window_size:
343-
end = np.clip(end, 0, num_values)
343+
end = np.clip(end, 0, num_values) # type: ignore[assignment]
344344

345345
return start, end
346346

@@ -426,7 +426,7 @@ def get_window_bounds(
426426
)
427427
window_indices_start += len(indices)
428428
# Extend as we'll be slicing window like [start, end)
429-
window_indices = np.append(window_indices, [window_indices[-1] + 1]).astype(
429+
window_indices = np.append(window_indices, [window_indices[-1] + 1]).astype( # type: ignore[assignment]
430430
np.int64, copy=False
431431
)
432432
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
@@ -1119,14 +1119,7 @@ def interval_range(
11191119
breaks = np.linspace(start, end, periods)
11201120
if all(is_integer(x) for x in com.not_none(start, end, freq)):
11211121
# np.linspace always produces float output
1122-
1123-
# error: Argument 1 to "maybe_downcast_numeric" has incompatible type
1124-
# "Union[ndarray[Any, Any], TimedeltaIndex, DatetimeIndex]";
1125-
# expected "ndarray[Any, Any]" [
1126-
breaks = maybe_downcast_numeric(
1127-
breaks, # type: ignore[arg-type]
1128-
np.dtype("int64"),
1129-
)
1122+
breaks = maybe_downcast_numeric(breaks, np.dtype("int64")) # type: ignore[arg-type]
11301123
else:
11311124
# delegate to the appropriate range function
11321125
if isinstance(endpoint, Timestamp):

pandas/core/internals/blocks.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2635,7 +2635,7 @@ def _unstack(
26352635
self.values.take(
26362636
indices, allow_fill=needs_masking[i], fill_value=fill_value
26372637
),
2638-
BlockPlacement(place),
2638+
BlockPlacement(place), # type: ignore[arg-type]
26392639
ndim=2,
26402640
)
26412641
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
@@ -712,7 +712,7 @@ def reorder_arrays(
712712
arr = np.empty(length, dtype=object)
713713
arr.fill(np.nan)
714714
else:
715-
arr = arrays[k]
715+
arr = arrays[k] # type: ignore[assignment]
716716
new_arrays.append(arr)
717717

718718
arrays = new_arrays

pandas/core/missing.py

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

244244
if is_valid.ndim == 2:
245-
is_valid = is_valid.any(axis=1) # reduce axis 1
245+
# reduce axis 1
246+
is_valid = is_valid.any(axis=1) # type: ignore[assignment]
246247

247248
if how == "first":
248249
idxpos = is_valid[::].argmax()
@@ -401,13 +402,7 @@ def func(yvalues: np.ndarray) -> None:
401402
**kwargs,
402403
)
403404

404-
# error: Argument 1 to "apply_along_axis" has incompatible type
405-
# "Callable[[ndarray[Any, Any]], None]"; expected "Callable[...,
406-
# Union[_SupportsArray[dtype[<nothing>]], Sequence[_SupportsArray
407-
# [dtype[<nothing>]]], Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]],
408-
# Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]],
409-
# Sequence[Sequence[Sequence[Sequence[_SupportsArray[dtype[<nothing>]]]]]]]]"
410-
np.apply_along_axis(func, axis, data) # type: ignore[arg-type]
405+
np.apply_along_axis(func, axis, data)
411406

412407

413408
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
@@ -360,7 +360,7 @@ def get_empty_frame(data) -> DataFrame:
360360

361361
if drop_first:
362362
# remove first GH12042
363-
dummy_mat = dummy_mat[:, 1:]
363+
dummy_mat = dummy_mat[:, 1:] # type: ignore[assignment]
364364
dummy_cols = dummy_cols[1:]
365365
return DataFrame(dummy_mat, index=index, columns=dummy_cols, dtype=_dtype)
366366

pandas/core/reshape/merge.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -2606,9 +2606,7 @@ def _convert_arrays_and_get_rizer_klass(
26062606
lk = lk.astype(dtype, copy=False)
26072607
rk = rk.astype(dtype, copy=False)
26082608
if isinstance(lk, BaseMaskedArray):
2609-
# Invalid index type "type" for "Dict[Type[object], Type[Factorizer]]";
2610-
# expected type "Type[object]"
2611-
klass = _factorizers[lk.dtype.type] # type: ignore[index]
2609+
klass = _factorizers[lk.dtype.type]
26122610
elif isinstance(lk.dtype, ArrowDtype):
26132611
klass = _factorizers[lk.dtype.numpy_dtype.type]
26142612
else:

pandas/core/sorting.py

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

483483
return _nanargminmax(arr_values, mask, func)

pandas/io/formats/format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1507,7 +1507,7 @@ def _format_strings(self) -> list[str]:
15071507
fmt_values = values._format_native_types(
15081508
na_rep=self.nat_rep, date_format=self.date_format
15091509
)
1510-
return fmt_values.tolist()
1510+
return fmt_values.tolist() # type: ignore[return-value]
15111511

15121512

15131513
class _ExtensionArrayFormatter(_GenericArrayFormatter):

pandas/io/parsers/python_parser.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1299,7 +1299,7 @@ def detect_colspecs(
12991299
shifted[0] = 0
13001300
edges = np.where((mask ^ shifted) == 1)[0]
13011301
edge_pairs = list(zip(edges[::2], edges[1::2]))
1302-
return edge_pairs
1302+
return edge_pairs # type: ignore[return-value]
13031303

13041304
def __next__(self) -> list[str]:
13051305
# 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
@@ -242,7 +242,7 @@ def _random_color(column: int) -> list[float]:
242242
"""Get a random color represented as a list of length 3"""
243243
# GH17525 use common._random_state to avoid resetting the seed
244244
rs = com.random_state(column)
245-
return rs.rand(3).tolist()
245+
return rs.rand(3).tolist() # type: ignore[return-value]
246246

247247

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

pandas/tests/dtypes/test_missing.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -810,8 +810,8 @@ def test_empty_like(self):
810810
np.datetime64("NaT"),
811811
np.timedelta64("NaT"),
812812
]
813-
+ [np.datetime64("NaT", unit) for unit in m8_units]
814-
+ [np.timedelta64("NaT", unit) for unit in m8_units]
813+
+ [np.datetime64("NaT", unit) for unit in m8_units] # type: ignore[call-overload]
814+
+ [np.timedelta64("NaT", unit) for unit in m8_units] # type: ignore[call-overload]
815815
)
816816

817817
inf_vals = [

0 commit comments

Comments
 (0)