Helper function to encode values into [0, n_uniques - 1]. Uses pure python method for object dtype, and numpy method for all other dtypes. The numpy method has the limitation that the `uniques` need to be sorted. Importantly, this is not checked but assumed to already be the cas
(values, *, uniques, check_unknown=True)
| 195 | |
| 196 | |
| 197 | def _encode(values, *, uniques, check_unknown=True): |
| 198 | """Helper function to encode values into [0, n_uniques - 1]. |
| 199 | |
| 200 | Uses pure python method for object dtype, and numpy method for |
| 201 | all other dtypes. |
| 202 | The numpy method has the limitation that the `uniques` need to |
| 203 | be sorted. Importantly, this is not checked but assumed to already be |
| 204 | the case. The calling method needs to ensure this for all non-object |
| 205 | values. |
| 206 | |
| 207 | Parameters |
| 208 | ---------- |
| 209 | values : ndarray |
| 210 | Values to encode. |
| 211 | uniques : ndarray |
| 212 | The unique values in `values`. If the dtype is not object, then |
| 213 | `uniques` needs to be sorted. |
| 214 | check_unknown : bool, default=True |
| 215 | If True, check for values in `values` that are not in `unique` |
| 216 | and raise an error. This is ignored for object dtype, and treated as |
| 217 | True in this case. This parameter is useful for |
| 218 | _BaseEncoder._transform() to avoid calling _check_unknown() |
| 219 | twice. |
| 220 | |
| 221 | Returns |
| 222 | ------- |
| 223 | encoded : ndarray |
| 224 | Encoded values |
| 225 | """ |
| 226 | xp, _ = get_namespace(values, uniques) |
| 227 | if not xp.isdtype(values.dtype, "numeric"): |
| 228 | try: |
| 229 | return _map_to_integer(values, uniques) |
| 230 | except KeyError as e: |
| 231 | raise ValueError(f"y contains previously unseen labels: {e}") |
| 232 | else: |
| 233 | if check_unknown: |
| 234 | diff = _check_unknown(values, uniques) |
| 235 | if diff: |
| 236 | raise ValueError(f"y contains previously unseen labels: {diff}") |
| 237 | return xp.searchsorted(uniques, values) |
| 238 | |
| 239 | |
| 240 | def _check_unknown(values, known_values, return_mask=False): |
searching dependent graphs…