Intended to be a drop-in replacement for np.argsort which handles NaNs. Adds ascending, na_position, and key parameters. (GH #6399, #5231, #27237) Parameters ---------- items : np.ndarray, ExtensionArray, Index, or Series kind : {'quicksort', 'mergesort', 'heapsort',
(
items: ArrayLike | Index | Series,
kind: SortKind = "quicksort",
ascending: bool = True,
na_position: str = "last",
key: Callable | None = None,
mask: npt.NDArray[np.bool_] | None = None,
)
| 370 | |
| 371 | |
| 372 | def nargsort( |
| 373 | items: ArrayLike | Index | Series, |
| 374 | kind: SortKind = "quicksort", |
| 375 | ascending: bool = True, |
| 376 | na_position: str = "last", |
| 377 | key: Callable | None = None, |
| 378 | mask: npt.NDArray[np.bool_] | None = None, |
| 379 | ) -> npt.NDArray[np.intp]: |
| 380 | """ |
| 381 | Intended to be a drop-in replacement for np.argsort which handles NaNs. |
| 382 | |
| 383 | Adds ascending, na_position, and key parameters. |
| 384 | |
| 385 | (GH #6399, #5231, #27237) |
| 386 | |
| 387 | Parameters |
| 388 | ---------- |
| 389 | items : np.ndarray, ExtensionArray, Index, or Series |
| 390 | kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, default 'quicksort' |
| 391 | ascending : bool, default True |
| 392 | na_position : {'first', 'last'}, default 'last' |
| 393 | key : Optional[Callable], default None |
| 394 | mask : Optional[np.ndarray[bool]], default None |
| 395 | Passed when called by ExtensionArray.argsort. |
| 396 | |
| 397 | Returns |
| 398 | ------- |
| 399 | np.ndarray[np.intp] |
| 400 | """ |
| 401 | |
| 402 | if key is not None: |
| 403 | # see TestDataFrameSortKey, TestRangeIndex::test_sort_values_key |
| 404 | items = ensure_key_mapped(items, key) |
| 405 | return nargsort( |
| 406 | items, |
| 407 | kind=kind, |
| 408 | ascending=ascending, |
| 409 | na_position=na_position, |
| 410 | key=None, |
| 411 | mask=mask, |
| 412 | ) |
| 413 | |
| 414 | if isinstance(items, ABCRangeIndex): |
| 415 | return items.argsort(ascending=ascending) |
| 416 | elif not isinstance(items, ABCMultiIndex): |
| 417 | items = extract_array(items) |
| 418 | else: |
| 419 | raise TypeError( |
| 420 | "nargsort does not support MultiIndex. Use index.sort_values instead." |
| 421 | ) |
| 422 | |
| 423 | if mask is None: |
| 424 | mask = np.asarray(isna(items)) |
| 425 | |
| 426 | if not isinstance(items, np.ndarray): |
| 427 | # i.e. ExtensionArray |
| 428 | return items.argsort( |
| 429 | ascending=ascending, |