How to remove NaN values from a given NumPy array? (original) (raw)
Last Updated : 14 Jan, 2026
Removing NaN values from a NumPy array is essential for accurate numerical computations and data analysis. NumPy provides efficient methods to identify and filter out missing values, ensuring clean and reliable datasets.
**Example:
**Input: [[5, nan, 8],
[2, 6, nan],
[nan, 1, 3]]**Output: [5. 8. 2. 6. 1. 3.]
Using ~np.isnan()
The ~ operator reverses the boolean array returned by np.isnan(), keeping only the non-NaN elements.
Python `
import numpy as np arr = np.array([[12, 5, np.nan, 7], [2, 61, 1, np.nan], [np.nan, 1, np.nan, 5]])
res = arr[~np.isnan(arr)] print("2D array converted to 1D after removing NaNs ->", res)
`
Output
2D array converted to 1D after removing NaNs -> [12. 5. 7. 2. 61. 1. 1. 5.]
**Explanation:
- **np.isnan(arr): Creates a boolean array with True where values are NaN.
- **~np.isnan(arr): Inverts the boolean result so True indicates valid (non-NaN) values.
- **arr[~np.isnan(arr)]: Selects and returns only the non-NaN elements.
- The result is flattened into a 1D array containing all valid numbers.
Using np.isfinite()
This method removes NaN and infinite values from a NumPy array. np.isfinite() returns True for all finite numbers, allowing you to keep only valid numeric elements.
Python `
import numpy as np arr = np.array([[12, 5, np.nan, 7], [2, 61, 1, np.nan], [np.nan, 1, np.nan, 5]])
res = arr[np.isfinite(arr)] print("2D array converted to 1D after removing NaNs ->", res)
`
Output
2D array converted to 1D after removing NaNs -> [12. 5. 7. 2. 61. 1. 1. 5.]
**Explanation: np.isfinite(arr): Returns True for all finite numbers (i.e., not NaN or Infinity).
Using numpy.logical_not() and numpy.isnan()
This method helps you filter out all NaN (Not a Number) values from a NumPy array. np.isnan() identifies the NaNs and np.logical_not() reverses the boolean result to select only the valid numbers.
Python `
import numpy as np
arr = np.array([[6, 2, np.nan], [2, 6, 1], [np.nan, 1, np.nan]]) res = arr[np.logical_not(np.isnan(arr))] print("2D array converted to 1D after removing NaNs ->", res)
`