Apply argmin or argmax over one or more dimensions, returning the result as a dict of DataArray that can be passed directly to isel.
(
self,
argminmax: str,
dim: Dims,
axis: int | None,
keep_attrs: bool | None,
skipna: bool | None,
)
| 2486 | return type(self)(self.dims, numeric_array, self._attrs) |
| 2487 | |
| 2488 | def _unravel_argminmax( |
| 2489 | self, |
| 2490 | argminmax: str, |
| 2491 | dim: Dims, |
| 2492 | axis: int | None, |
| 2493 | keep_attrs: bool | None, |
| 2494 | skipna: bool | None, |
| 2495 | ) -> Variable | dict[Hashable, Variable]: |
| 2496 | """Apply argmin or argmax over one or more dimensions, returning the result as a |
| 2497 | dict of DataArray that can be passed directly to isel. |
| 2498 | """ |
| 2499 | if dim is None and axis is None: |
| 2500 | warnings.warn( |
| 2501 | "Behaviour of argmin/argmax with neither dim nor axis argument will " |
| 2502 | "change to return a dict of indices of each dimension. To get a " |
| 2503 | "single, flat index, please use np.argmin(da.data) or " |
| 2504 | "np.argmax(da.data) instead of da.argmin() or da.argmax().", |
| 2505 | FutureWarning, |
| 2506 | stacklevel=3, |
| 2507 | ) |
| 2508 | |
| 2509 | argminmax_func = getattr(duck_array_ops, argminmax) |
| 2510 | |
| 2511 | if dim is ...: |
| 2512 | # In future, should do this also when (dim is None and axis is None) |
| 2513 | dim = self.dims |
| 2514 | if ( |
| 2515 | dim is None |
| 2516 | or axis is not None |
| 2517 | or not isinstance(dim, Sequence) |
| 2518 | or isinstance(dim, str) |
| 2519 | ): |
| 2520 | # Return int index if single dimension is passed, and is not part of a |
| 2521 | # sequence |
| 2522 | return self.reduce( |
| 2523 | argminmax_func, dim=dim, axis=axis, keep_attrs=keep_attrs, skipna=skipna |
| 2524 | ) |
| 2525 | |
| 2526 | # Get a name for the new dimension that does not conflict with any existing |
| 2527 | # dimension |
| 2528 | newdimname = "_unravel_argminmax_dim_0" |
| 2529 | count = 1 |
| 2530 | while newdimname in self.dims: |
| 2531 | newdimname = f"_unravel_argminmax_dim_{count}" |
| 2532 | count += 1 |
| 2533 | |
| 2534 | stacked = self.stack({newdimname: dim}) |
| 2535 | |
| 2536 | result_dims = stacked.dims[:-1] |
| 2537 | reduce_shape = tuple(self.sizes[d] for d in dim) |
| 2538 | |
| 2539 | result_flat_indices = stacked.reduce(argminmax_func, axis=-1, skipna=skipna) |
| 2540 | |
| 2541 | result_unravelled_indices = duck_array_ops.unravel_index( |
| 2542 | result_flat_indices.data, reduce_shape |
| 2543 | ) |
| 2544 | |
| 2545 | result = { |