{"id":123450,"date":"2022-03-31T07:10:26","date_gmt":"2022-03-31T07:10:26","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=273492"},"modified":"2022-03-31T07:10:26","modified_gmt":"2022-03-31T07:10:26","slug":"check-for-nan-values-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/03\/31\/check-for-nan-values-in-python\/","title":{"rendered":"Check for NaN Values in Python"},"content":{"rendered":"<h2><strong>Overview<\/strong><\/h2>\n<p><strong>Problem<\/strong>: How to check if a given value is <code>NaN<\/code>?<\/p>\n<p>Here&#8217;s a quick look at the solutions to follow:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import math\nimport numpy as np\nimport pandas as pd x = float('nan')\nprint(math.isnan(x))\nprint(x != x)\nprint(np.isnan(x))\nprint(pd.isna(x))\nprint(not(float('-inf') &lt; x &lt; float('inf')))<\/pre>\n<p>So, what is a <code>NaN<\/code> value?<\/p>\n<p><code>NaN<\/code> is a constant value that indicates that the given value is Not a Number. It&#8217;s a floating-point value, hence cannot be converted to any other type other than float. We should know that <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code> and Null are two different things in Python. The Null values indicate something which does not exist, i.e. is empty. But that is not the case with <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code>.<\/p>\n<p>We have to deal with <code>NaN<\/code> values frequently in Python especially when we deal with array objects or DataFrames. So, without further delay, let us dive into our mission critical question and have a look at the different methods to solve our problem.<\/p>\n<h2><strong>Method 1: Using math.isnan()<\/strong><\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The simplest solution to check for NaN values in Python is to use the mathematical function <code>math.isnan()<\/code>.<\/p>\n<p><code>math.isnan()<\/code> is a function of the math module in Python that checks for <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code> constants in float objects and returns True for every NaN value encountered and returns False otherwise. <\/p>\n<p><strong>Example: <\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Importing the math module\nimport math # Function to check for NaN values\ndef isNaN(a): # Using math.isnan() if math.isnan(a): print(\"NaN value encountered!\") else: print(\"Type of Given Value: \", type(a)) # NaN value\nx = float('NaN')\nisNaN(x)\n# Floating value\ny = float(\"5.78\")\nisNaN(y)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>NaN value encountered!\nType of Given Value: &lt;class 'float'&gt;<\/code><\/pre>\n<p>In the above example, since <code>x<\/code> represents a NaN value, hence, the <code>isNaN<\/code> method returns <code>True<\/code> but in case of <code>y<\/code> , <code>isNan<\/code> returns <code>False<\/code> and prints the type of the variable <code>y<\/code> as an output. <\/p>\n<h2><strong>Method 2: Hack NaN Using != Operator<\/strong><\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The most unique thing about <code>NaN<\/code> values is that they are constantly shapeshifting. This means we cannot compare the <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code> value even against itself. Hence, we can use the <code>!=<\/code> (not equal to) operator to check for the <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code> values. Thus, the idea is to check if the given variable is equal to itself. If we consider any object other than <code>NaN<\/code>, the expression <code>(x == x)<\/code> will always return <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">True<\/code>. If it&#8217;s not equal, then it is a <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code> value. <\/p>\n<p><strong>Example 1:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print(5 == 5)\n# True\nprint(['a', 'b'] == ['a', 'b'])\n# True\nprint([] == [])\n# True\nprint(float(\"nan\") == float(\"nan\"))\n# False\nprint(float(\"nan\") != float(\"nan\"))\n# True<\/pre>\n<p><strong>Example 2:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Function to check for NaN values\ndef not_a_number(x): # Using != operator if x != x: print(\"Not a Number!\") else: print(f'Type of {x} is {type(x)}') # Floating value\nx = float(\"7.8\")\nnot_a_number(x)\n# NaN value\ny = float(\"NaN\")\nnot_a_number(y)<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>Type of 7.8 is &lt;class 'float'&gt;\nNot a Number!<\/code><\/pre>\n<h2><strong>Method 3: Using <a href=\"https:\/\/blog.finxter.com\/numpy-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">numpy<\/a>.isnan()<\/strong><\/h2>\n<p>We can also use the <code>NumPy<\/code> library to check whether the given value is <code>NaN<\/code> or not. We just need to ensure that we import the library at the start of the program and then use its <code>np.isnan(x)<\/code> method. <\/p>\n<p class=\"has-global-color-8-background-color has-background\">The <code>np.isnan(number)<\/code> function checks whether the element in a Numpy array is <code>NaN<\/code> or not. It then returns the result as a boolean array.<\/p>\n<p><strong>Example: <\/strong>In the following example we have a Numpy Array and then we will check the type of each value. We will also check if it is a <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code> value or not.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])\nfor x in arr: if np.isnan(x): print(\"Not a Number!\") else: print(x, \":\", type(x))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>10.0 : &lt;class 'numpy.float64'&gt;\n20.0 : &lt;class 'numpy.float64'&gt;\nNot a Number!\n40.0 : &lt;class 'numpy.float64'&gt;\nNot a Number!<\/code><\/pre>\n<p><strong><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/>TRIVIA<\/strong><\/p>\n<p>Let us try to perform some basic functions on an numpy array that involves <code>NaN<\/code> values and find out what happens to it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])\nprint(arr.sum())\nprint(arr.max())<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>nan\nnan<\/code><\/pre>\n<p>Now this can be a problem in many cases. So, do we have a way to eliminate the NaN values from our array object and then perform the mathematical operations upon the array elements? <strong>Yes! <\/strong>Numpy facilitates us with methods like <code>np.nansum()<\/code> and <code>np.nanmax()<\/code> that help us to calculate the sum and maximum values in the array by ignoring the presence of <code>NaN<\/code> values in the array.<\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import numpy as np arr = np.array([10, 20, np.nan, 40, np.nan])\nprint(np.nansum(arr))\nprint(np.nanmax(arr))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>70.0\n40.0<\/code><\/pre>\n<h2><strong><strong>Method 4: Using <a href=\"https:\/\/blog.finxter.com\/pandas-quickstart\/\" target=\"_blank\" rel=\"noreferrer noopener\">pandas<\/a>.isna()<\/strong><\/strong><\/h2>\n<p>Another way to solve our problem is to use the <code>isna()<\/code> method of the Pandas module. <code>pandas.isna()<\/code> is a function that detects missing values in an array-like object. It returns True if any <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN<\/code> value is encountered. <\/p>\n<p><strong>Example 1:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pandas as pd x = float(\"nan\")\ny = 25.75\nprint(pd.isna(x))\nprint(pd.isna(y))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>True\nFalse<\/code><\/pre>\n<p><strong>Example 2: <\/strong>In the following example we will have a look at a Pandas DataFrame and detect the presence of NaN values in the DataFrame.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pandas as pd df = pd.DataFrame([['Mercury', 'Venus', 'Earth'], ['1', float('nan'), '2']])\nprint(pd.isna(df))<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code> 0 1 2\n0 False False False\n1 False True False<\/code><\/pre>\n<h2><strong>Method 5: By Checking The Range<\/strong><\/h2>\n<p>We can check for the <code>NaN<\/code> values by using another NaN special property: limited range. The range of all the floating-point values falls within negative infinity to infinity. However, <code>NaN<\/code> values do not fall within this range. <\/p>\n<p class=\"has-global-color-8-background-color has-background\">Hence, the idea is to check whether a given value lies within the range of <code>-inf<\/code> and <code>inf<\/code>. If yes , then it is not a <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN <\/code>value else it is a <code data-enlighter-language=\"generic\" class=\"EnlighterJSRAW\">NaN <\/code>value. <\/p>\n<p><strong>Example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">li = [25.87, float('nan')]\nfor i in li: if float('-inf') &lt; float(i) &lt; float('inf'): print(i) else: print(\"Not a Number!\")<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>25.87\nNot a Number!<\/code><\/pre>\n<p class=\"has-background\" style=\"background-color:#fdfeb7\"><strong>Recommended read: <a href=\"https:\/\/blog.finxter.com\/python-infinity\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Infinity<\/a><\/strong><\/p>\n<h2><strong>Conclusion<\/strong><\/h2>\n<p>In this article, we learned how we can use the various methods and modules (<code>pandas<\/code>, <code>NumPy<\/code>, and <code>math<\/code>) in Python to check for the <code>NaN<\/code> values. I hope this article was able to answer your queries. Please <strong><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\" target=\"_blank\">stay tuned<\/a><\/strong> and <strong><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/subscribe\/\" target=\"_blank\">subscribe<\/a><\/strong> for more such articles.\u00a0<\/p>\n<p class=\"has-text-align-center has-contrast-3-background-color has-background has-small-font-size\"><strong>Authors: SHUBHAM SAYON and RASHI AGARWAL<\/strong><\/p>\n<hr class=\"wp-block-separator\" \/>\n<p><strong>Do you want to become a NumPy master?<\/strong> Check out our interactive puzzle book <a href=\"https:\/\/amzn.to\/39dEykm\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/39dEykm\"><strong>Coffee Break NumPy<\/strong><\/a> and boost your data science skills! <em>(Amazon link opens in new tab.)<\/em><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-medium\"><a href=\"https:\/\/amzn.to\/39dEykm\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" width=\"200\" height=\"300\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/04\/Cover_Coffee_Break_NumPy-200x300.jpg\" alt=\"Coffee Break NumPy\" class=\"wp-image-2766\"\/><\/a><\/figure>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Overview Problem: How to check if a given value is NaN? Here&#8217;s a quick look at the solutions to follow: import math import numpy as np import pandas as pd x = float(&#8216;nan&#8217;) print(math.isnan(x)) print(x != x) print(np.isnan(x)) print(pd.isna(x)) print(not(float(&#8216;-inf&#8217;) &lt; x &lt; float(&#8216;inf&#8217;))) So, what is a NaN value? NaN is a constant value [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-123450","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123450","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=123450"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123450\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=123450"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=123450"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=123450"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}