当前位置:网站首页>[numpy] numpy's judgment on Nan value

[numpy] numpy's judgment on Nan value

2022-06-24 03:44:00 When Camellia blossoms.

Enjoy the beautiful picture 2022/06/23

numpy.nan The data type of is float type

import numpy as np
type(np.nan) # float

Any number and numpy.nan Calculate , All the returned results are nan

import numpy as np
print(np.nan + 1) # nan 
print(np.nan - 1) # nan 
print(np.nan * 1) # nan 
print(np.nan / 1) # nan 

For null values NaN The judgment of cannot be used directly == expression ,bool expression , And can not be used directly if sentence Judge

import numpy as np
np.nan == np.nan # False

bool(np.nan) # True

#  Output results :na is not null
if np.nan:
    print('np.nan is not null')  

Need to use Numpy Own method np.isnan(),is expression ,in expression Judge

import numpy as np
np.nan is np.nan # True
np.isnan(np.nan) # True
np.nan in [np.nan] # True

Tips

If you use Pandas To judge numpy.nan, You can use pd.isnull(),pd.isna() 

import numpy as np
import pandas as pd
pd.isnull(np.nan)  # True
pd.isna(np.nan)  # True

Be careful :None、NaN、'' The difference between empty strings

# None yes Python Special types of 
# NoneType object , It has only one value None
type(None) # NoneType
None == None # True
None == np.nan # False

#  An empty string ''
type('') # str

Pandas Medium pd.isnull Not only can it be detected np.nan It can also detect None, but Cannot detect string , such as '','nan','None' 

import pandas as pd
import numpy as np
pd.isnull(np.nan) # True
pd.isnull(None) # True
pd.isnull('') # False
pd.isnull('np.nan') # False
pd.isnull('None') # False
import pandas as pd
import numpy as np
List = ['nan', '', 'None', None, np.nan]
for i in List:
    if i == '' or pd.isnull(i) or pd.isnull(float('nan')) or i == 'None':
        print(i)

#  The above output results :
# nan
# ''
# None
# None
# nan

List(5 elements) 

原网站

版权声明
本文为[When Camellia blossoms.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206232329524814.html