VOOZH about

URL: https://www.geeksforgeeks.org/python/how-to-remove-nan-values-from-a-given-numpy-array/

⇱ How to remove NaN values from a given NumPy array? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to remove NaN values from a given NumPy array?

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.


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.


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.


Output
2D array converted to 1D after removing NaNs -> [6. 2. 2. 6. 1. 1.]

Explanation:

  • np.isnan(arr): Gives True for NaN elements.
  • np.logical_not(...): Reverses that boolean mask, so True for valid numbers.

Related Articles

Comment