Nice programing

NaN 값을 어떻게 확인할 수 있습니까?

nicepro 2020. 9. 28. 10:09
반응형

NaN 값을 어떻게 확인할 수 있습니까?


float('nan')결과는 Nan (숫자가 아님)입니다. 하지만 어떻게 확인합니까? 매우 쉬울 것이지만 찾을 수 없습니다.


math.isnan (x)

반환 Truex는 NaN (숫자), 및 경우 False그렇지.

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True

NaN을 테스트하는 일반적인 방법은 자신과 동일한 지 확인하는 것입니다.

def isNaN(num):
    return num != num

numpy.isnan(number)NaN그렇지 않은지 알려줍니다 .


나는 실제로 이것을 만났지만 나를 위해 nan, -inf 또는 inf를 확인했습니다. 나는 방금 사용했다

if float('-inf') < float(num) < float('inf'):

이것은 숫자에 대해 true이고 nan과 inf 모두에 대해 false이며 문자열이나 다른 유형 (아마도 좋은 일입니다)과 같은 것에 대해 예외를 발생시킵니다. 또한 이것은 math 또는 numpy와 같은 라이브러리를 가져올 필요가 없습니다 (numpy는 너무 커서 컴파일 된 응용 프로그램의 크기가 두 배가됩니다).


여기에 대한 답변이 있습니다.

  • python 고유하지 않은 NaN :float('nan')
  • numpy 고유 한 NaN (싱글 톤) :np.nan
  • 기타 객체 : 문자열 또는 기타 (만나면 예외를 발생시키지 않음)

여기있어:

import numpy as np

def is_nan(x):
    return (x is np.nan or x != x)

그리고 몇 가지 예 :

values = [float('nan'), np.nan, 55, "string", lambda x : x]
for value in values:
    print "{:<8} : {}".format(repr(value), is_nan(value))

산출:

nan      : True
nan      : True
55       : False
'string' : False
<function <lambda> at 0x000000000927BF28> : False

math.isnan ()

또는 숫자를 자신과 비교하십시오. NaN이 항상입니다! = (이 경우 예를 들어, NaN를, 그렇지 않으면 입니다 숫자) 비교 성공한다.


다음은 변수가 "NaN"인지 아닌지 테스트 할 수있는 세 가지 방법입니다.

import pandas as pd
import numpy as np
import math

#For single variable all three libraries return single boolean
x1 = float("nan")

print(f"It's pd.isna  : {pd.isna(x1)}")
print(f"It's np.isnan  : {np.isnan(x1)}")
print(f"It's math.isnan : {math.isnan(x1)}")

산출

It's pd.isna  : True
It's np.isnan  : True
It's math.isnan  : True

2.6 미만에서 멈춰 있고 numpy가없고 IEEE 754 지원이없는 경우 다른 방법 :

def isNaN(x):
    return str(x) == str(1e400*0)

기능에 몇 가지 문제가 있었기 때문에이 게시물을 입력했습니다.

math.isnan()

이 코드를 실행할 때 문제가 있습니다.

a = "hello"
math.isnan(a)

예외가 발생합니다. 이에 대한 내 해결책은 또 다른 확인을하는 것입니다.

def is_nan(x):
    return isinstance(x, float) and math.isnan(x)

파이썬 2.6 미만에서는

def isNaN(x):
    return str(float(x)).lower() == 'nan'

이것은 Solaris 5.9 상자의 python 2.5.1과 Ubuntu 10의 python 2.6.5에서 작동합니다.


I am receiving the data from a web-service that sends NaN as a string 'Nan'. But there could be other sorts of string in my data as well, so a simple float(value) could throw an exception. I used the following variant of the accepted answer:

def isnan(value):
  try:
      import math
      return math.isnan(float(value))
  except:
      return False

Requirement:

isnan('hello') == False
isnan('NaN') == True
isnan(100) == False
isnan(float('nan')) = True

All the methods to tell if the variable is NaN or None:

None type

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN type

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

How to remove NaN (float) item(s) from a list of mixed data types

If you have mixed types in an iterable, here is a solution that does not use numpy:

from math import isnan

Z = ['a','b', float('NaN'), 'd', float('1.1024')]

[x for x in Z if not (
                      type(x) == float # let's drop all float values…
                      and isnan(x) # … but only if they are nan
                      )]
['a', 'b', 'd', 1.1024]

Short-circuit evaluation means that isnan will not be called on values that are not of type 'float', as False and (…) quickly evaluates to False without having to evaluate the right-hand side.


For nan of type float

>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False

for strings in panda take pd.isnull:

if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):

the function as feature extraction for NLTK

def act_features(atext):
features = {}
if not pd.isnull(atext):
  for word in nltk.word_tokenize(atext):
    if word not in default_stopwords:
      features['cont({})'.format(word.lower())]=True
return features

참고URL : https://stackoverflow.com/questions/944700/how-can-i-check-for-nan-values

반응형