Python-Numpy空值判断

错误的方法

1
2
3
4
5
import numpy as np
data_list = np.asarray([1.1, 2.2, 0, np.nan, 3.3])
print(data_list)
a = data_list[np.where(data_list != np.nan)]
print(a)

运行结果如下

1
2
[1.1 2.2 0.  nan 3.3]
[1.1 2.2 0. nan 3.3]

# 正确的方法

原理1:利用 np.isnan()

原理2:利用 np.nan != np.nan

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np
data_list = np.asarray([1.1, 2.2, 0, np.nan, 3.3])
print(data_list)

# solution: using np.isnan()
print("\nthis is solution by np.isnan()")
print(np.isnan(data_list))
a = data_list[np.where(np.isnan(data_list) == False)]
print(a)


# solution 1, using np.nan != np.nan
print("\nthis is solution by np.nan != np.nan")
a = data_list[np.where(data_list == data_list)]
print(a)

输出为:

1
2
3
4
5
6
7
8
[1.1 2.2 0.  nan 3.3]

this is solution by np.isnan()
[False False False True False]
[1.1 2.2 0. 3.3]

this is solution by np.nan != np.nan
[1.1 2.2 0. 3.3]
Thanks for rewarding