Ranks the data. Equal values are assigned a rank that is the average of the ranks that would have been otherwise assigned to all of the values within that set. Ranks begin at 1, not 0. If `pct`, computes percentage ranks. NaNs in the input array are returned as NaN
(self, dim, pct=False)
| 2064 | return result |
| 2065 | |
| 2066 | def rank(self, dim, pct=False): |
| 2067 | """Ranks the data. |
| 2068 | |
| 2069 | Equal values are assigned a rank that is the average of the ranks that |
| 2070 | would have been otherwise assigned to all of the values within that |
| 2071 | set. Ranks begin at 1, not 0. If `pct`, computes percentage ranks. |
| 2072 | |
| 2073 | NaNs in the input array are returned as NaNs. |
| 2074 | |
| 2075 | The `bottleneck` library is required. |
| 2076 | |
| 2077 | Parameters |
| 2078 | ---------- |
| 2079 | dim : str |
| 2080 | Dimension over which to compute rank. |
| 2081 | pct : bool, optional |
| 2082 | If True, compute percentage ranks, otherwise compute integer ranks. |
| 2083 | |
| 2084 | Returns |
| 2085 | ------- |
| 2086 | ranked : Variable |
| 2087 | |
| 2088 | See Also |
| 2089 | -------- |
| 2090 | Dataset.rank, DataArray.rank |
| 2091 | """ |
| 2092 | # This could / should arguably be implemented at the DataArray & Dataset level |
| 2093 | if not OPTIONS["use_bottleneck"]: |
| 2094 | raise RuntimeError( |
| 2095 | "rank requires bottleneck to be enabled." |
| 2096 | " Call `xr.set_options(use_bottleneck=True)` to enable it." |
| 2097 | ) |
| 2098 | |
| 2099 | import bottleneck as bn |
| 2100 | |
| 2101 | func = bn.nanrankdata if self.dtype.kind == "f" else bn.rankdata |
| 2102 | ranked = xr.apply_ufunc( |
| 2103 | func, |
| 2104 | self, |
| 2105 | input_core_dims=[[dim]], |
| 2106 | output_core_dims=[[dim]], |
| 2107 | dask="parallelized", |
| 2108 | kwargs=dict(axis=-1), |
| 2109 | ).transpose(*self.dims) |
| 2110 | |
| 2111 | if pct: |
| 2112 | count = self.notnull().sum(dim) |
| 2113 | ranked /= count |
| 2114 | return ranked |
| 2115 | |
| 2116 | @_deprecate_positional_args("v2024.11.0") |
| 2117 | def rolling_window( |