Detecting Missing Values in NumPy (isnan, isfinite)

NumPy provides functions to detect missing or undefined values such as np.nan (Not a Number) and check for finite numbers using np.isnan() and np.isfinite().

1. Importing NumPy

Before using NumPy's missing value detection functions, import the module.

            import numpy as np
        

2. Detecting NaN Values with np.isnan()

The np.isnan() function checks for np.nan values in an array and returns a boolean array.

            arr = np.array([1, np.nan, 3, np.nan, 5])
            
            result = np.isnan(arr)
            print(result)
            # Output: [False  True False  True False]
        

3. Detecting Finite Values with np.isfinite()

The np.isfinite() function checks if elements in an array are finite (i.e., not np.nan or np.inf).

            arr = np.array([1, np.nan, np.inf, -np.inf, 4])
            
            result = np.isfinite(arr)
            print(result)
            # Output: [ True False False False  True]
        

4. Filtering Out NaN Values

To remove np.nan values from an array, use boolean indexing.

            arr = np.array([1, 2, np.nan, 4, np.nan, 6])
            
            filtered_arr = arr[~np.isnan(arr)]
            print(filtered_arr)
            # Output: [1. 2. 4. 6.]
        

5. Conclusion

NumPy provides np.isnan() to detect missing values and np.isfinite() to check for finite values, helping in data cleaning and preprocessing.





Advertisement