- What is the numpy.isnan() Method in Python
- Return Value
- Example 1: How to Use numpy.isnan() method
- Example 2
- numpy.isnan#
- Check if a NumPy Array contains any NaN value
- Table of Contents
- What is a NaN value?
- Check if a NumPy Array contains any NaN value using isnan() method
- Frequently Asked:
- Syntax of isnan()
- Parameters:
- Return:
- Syntax of any()
- Parameters:
- Return:
- Approach
- Source code
- OUTPUT:
- Check if a NumPy array contains any NaN value using isna() method
- Syntax of isna()
- Parameters:
- Return:
- Approach
- Source code
- OUTPUT:
- Check if a NumPy array has any NaN value using isnan() method of math module
- Approach
- Source code
- OUTPUT:
- Check the equality of the value with itself to check if a NumPy array contains any NaN value.
- Approach
- Source code
- OUTPUT:
- Summary
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
What is the numpy.isnan() Method in Python
input_array: The first parameter is the input array or the input for which we want to check whether it is NaN. The second one is the n-dimensional array, which is optional. Finally, it is the output array that is placed with the result.
Return Value
The Numpy isnan() method returns a Boolean array, which has the result if we pass the array and Boolean value true or false if we pass a scalar value according to the value passed.
Example 1: How to Use numpy.isnan() method
import numpy as np print("NaN value - : ", np.isnan(933), "\n") # Scalar Values print("NaN value - : ", np.isnan(444), "\n") print("NaN value - : ", np.isnan(np.inf), "\n") # checking for infinity value print("NaN value - : ", np.isnan(np.NINF), "\n") print("NaN value - : ", np.isnan(np.nan)) # Checking for nan values
NaN value - : False NaN value - : False NaN value - : False NaN value - : False NaN value - : True
Example 2
import numpy as np arr = np.arange(24).reshape(6, 4) print("List = ", arr) print("\n") print("Is NaN - ", np.isnan(arr))
List = [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15] [16 17 18 19] [20 21 22 23]] Is NaN - [[False False False False] [False False False False] [False False False False] [False False False False] [False False False False] [False False False False]]
In this example, we can see that by creating a list of 24 elements, we have checked whether each element contains a NaN value.
numpy.isnan#
Test element-wise for NaN and return result as a boolean array.
Parameters : x array_like
out ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.
where array_like, optional
This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None , locations within it where the condition is False will remain uninitialized.
For other keyword-only arguments, see the ufunc docs .
Returns : y ndarray or bool
True where x is NaN, false otherwise. This is a scalar if x is a scalar.
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity.
>>> np.isnan(np.nan) True >>> np.isnan(np.inf) False >>> np.isnan([np.log(-1.),1.,np.log(0)]) array([ True, False, False])
Check if a NumPy Array contains any NaN value
In this article, We will learn how to check if a NumPy Array contains any NaN value in Python.
Table of Contents
What is a NaN value?
The NaN stands for Not a Number, which is a numeric data type that can be interpreted as a value that is undefined or unrepresentable.
Usually NaN values are used to represent the missing data in a dataframe or a NumPy Array.
Given a NumPy array, we need to check if the NumPy Array contains any NaN value or not.
Example: Given array = [1, 2, 3, 4, NaN, 5, 6] The Array has NaN value at 5th position.
There are multiple ways to check if a NumPy Array contains any NaN value. Let’s discuss all the methods one by one with a proper approach and a working code example.
Check if a NumPy Array contains any NaN value using isnan() method
Numpy module in python, provides a function numpy.isnan(), to check if an element is NaN or not. The isnan() method will take a array as an input and returns a boolean array of same size. The values in boolean array represent that if the element at that corresponding position in original array is a NaN or not. The value in boolean array is True where element is NaN, false otherwise.
Frequently Asked:
Syntax of isnan()
Parameters:
arr = The input array to be passed to the function.
Return:
Returns a boolean array, True where element is NaN, false otherwise.
As this method returns a boolean array, we need to check if the array contain atleast one true value i.e, NaN value. The any() method can be used to find if there is at least one true value. The any() method returns True if any item in an array is true, otherwise it returns False.
Syntax of any()
Parameters:
arr = The input array to be passed to the function.
Return:
Returns a boolean value, True if any item in an array are true, otherwise it returns False.
Approach
- Import numpy library and create a numpy array
- Now pass the array to the isnan() method. It will return a boolean array. Where True value denotes the NaN values in original array.
- Pass the boolean array to the any() method, and it will returns a boolean value
- If the value is true print “Array has NaN values” else print “Array has no NaN values.”
Source code
import numpy as np # Creating a NumPy array arr = np.array([1, 2, 3, 4, np.NaN, 5, 6]) # Check if the NumPy array contains any NaN value if(np.isnan(arr).any()): print("The Array contain NaN values") else: print("The Array does not contain NaN values")
OUTPUT:
The Array contain NaN values
Check if a NumPy array contains any NaN value using isna() method
Pandas module in python, provides a function Pandas.isna(), to check if a element is NaN or not. The isna() method will take an array as an input and returns a boolean array. The values in boolean array represent that if the element at that corresponding position in original array is a NaN or not. The value in boolean array is True where element is NaN and false otherwise.
Syntax of isna()
Parameters:
arr = The input array to be passed to the function.
Return:
Returns a boolean array. It will contain True where element is NaN in original array, false otherwise.
As the method returns a boolean array, we need to check if the array contain at least one true value i.e, NaN value. The any() method can be used to find if there is at least one true value. The any(arr) accepts a numpy array as argument and method returns True if any item in an array is True, otherwise it returns False.
Approach
- Import numpy library and create a numpy array
- Now pass the array to the isna() method. It will return a boolean array. Where True value denotes the NaN values in original array.
- Pass the boolean array to the any method, the any() will returns a boolean value
- If the value is true print “Array has NaN values” else print “Array has no NaN values.”
Source code
import pandas as pd import numpy as np # Creating a NumPy array arr = np.array([1, 2, 3, 4, np.NaN, 5, 6]) # Check if the NumPy array contains any NaN value if(pd.isna(arr).any()): print("The Array contain NaN values") else: print("The Array does not contain NaN values")
OUTPUT:
The Array contain NaN values
Check if a NumPy array has any NaN value using isnan() method of math module
Math module in python, provides a function math.isnan() to check if a element is NaN or not. The isnan() method will take a value as an input and returns a boolean value, The returned boolean value True if the element is NaN, false otherwise..
Now to check if there is any NaN in a NumPy Array, using a for loop, we will iterate over the array and apply isnan() method too each element in the array, if any element is NaN then break the loop and print the array has NaN values.
Approach
- Import numpy library and create a numpy array
- Initialise a boolean flag contain = False.
- Iterate over the array using a loop and apply isnan() on each element. The isnan() will return a boolean value
- If the returned value is true, set the boolean flag to True and print “Array has NaN values” and break the loop.
- Outside the loop, check the contain flag, if it is False print “Array has no NaN values”
Source code
import numpy as np import math # Create a NumPy array arr = np.array([1, 2, 3, 4, np.NaN, 5, 6]) # Check if the NumPy array contains any NaN value contain=False for i in arr: if(math.isnan(i)): contain = True break if(contain): print("The Array contain NaN values") else: print("The Array does not contain NaN values")
OUTPUT:
The Array contain NaN values
Check the equality of the value with itself to check if a NumPy array contains any NaN value.
When a value is checked for equality with itself, it will return True, but in the case of the NaN value, even when it are compared with itself, it will return False.
Now to check if there is a NaN in array, using a for loop we will iterate over the array and compare each element with itself using a equality operator. If any value is not equal with itself then it is a NaN value and print array has NaN values.
Approach
- Import numpy library and create a numpy array
- Initialize a boolean flag contain = False.
- Iterate over the array using a loop and check for equality with itself
- If the values are Not equal, set the boolean flag to True and print “Array has NaN values” and break the loop.
- Outside the check the contain flag, if it is False print “Array has no NaN values”.
Source code
#importing the numpy library import numpy as np # creating numpy array arr = np.array([1, 2, 3, 4, np.NaN, 5, 6]) # Checking if the NumPy array contains any NaN value contain= False for i in arr: if ( i!=i ): contain = True break if(contain): print("The Array contain NaN values") else: print("The Array does not contain NaN values")
OUTPUT:
The Array contain NaN values
Summary
Great! you made it, We have discussed all possible methods to check if a NumPy array contains any NaN value or not. Happy learning.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.