Counting the number of non-NaN elements in a NumPy Array
In this article, we are going to see how to count the number of non-NaN elements in a NumPy array in Python.
NAN: It is used when you don’t care what the value is at that position. Maybe sometimes is used in place of missing data, or corrupted data.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Method 1: Using Condition
In this example, we will use one-dimensional arrays. In the below-given code, we loop over every entry of the given NumPy array and check if the value is a NaN or not.
Method 2: Using isnan()
Using the functionality of NumPy arrays, that we can perform an operation on the whole array at once, instead of a single element.
- np.isnan(data): Returns a boolean array after performing np.isnan() operation on of the entries of the array, data
- np.sum(): Since we are inputting a boolean array to the sum function, it returns the number of True values (1s) in the bool array.
Method 3: Using np.count_nonzero() function
numpy.count_nonzero() function counts the number of non-zero values in the array arr.
Syntax : numpy.count_nonzero(arr, axis=None)
arr : [array_like] The array for which to count non-zeros.
axis : [int or tuple, optional] Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of arr.
Return : [int or array of int] Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned.