Aluode/PerceptionLabPortable
0
1# Authors: The scikit-learn developers
2# SPDX-License-Identifier: BSD-3-Clause
3
4import math
5import numbers
6from contextlib import suppress
7
8
9def is_scalar_nan(x):
10 """Test if x is NaN.
11
12 This function is meant to overcome the issue that np.isnan does not allow
13 non-numerical types as input, and that np.nan is not float('nan').
14
15 Parameters
16 ----------
17 x : any type
18 Any scalar value.
19
20 Returns
21 -------
22 bool
23 Returns true if x is NaN, and false otherwise.
24
25 Examples
26 --------
27 >>> import numpy as np
28 >>> from sklearn.utils._missing import is_scalar_nan
29 >>> is_scalar_nan(np.nan)
30 True
31 >>> is_scalar_nan(float("nan"))
32 True
33 >>> is_scalar_nan(None)
34 False
35 >>> is_scalar_nan("")
36 False
37 >>> is_scalar_nan([np.nan])
38 False
39 """
40 return (
41 not isinstance(x, numbers.Integral)
42 and isinstance(x, numbers.Real)
43 and math.isnan(x)
44 )
45
46
47def is_pandas_na(x):
48 """Test if x is pandas.NA.
49
50 We intentionally do not use this function to return `True` for `pd.NA` in
51 `is_scalar_nan`, because estimators that support `pd.NA` are the exception
52 rather than the rule at the moment. When `pd.NA` is more universally
53 supported, we may reconsider this decision.
54
55 Parameters
56 ----------
57 x : any type
58
59 Returns
60 -------
61 boolean
62 """
63 with suppress(ImportError):
64 from pandas import NA
65
66 return x is NA
67
68 return False
69 