Home >Backend Development >Python Tutorial >How to Exclude NaN Values from NumPy Arrays?

How to Exclude NaN Values from NumPy Arrays?

Susan Sarandon
Susan SarandonOriginal
2024-10-18 16:22:29650browse

How to Exclude NaN Values from NumPy Arrays?

Excluding NaN Values from NumPy Arrays

NaN (Not-a-Number) values can arise in numerical computations, leading to undesired results. Removing NaN values from NumPy arrays is crucial for data integrity and further analysis.

How to Remove NaN Values:

To effectively eliminate NaN values from a NumPy array named x, leverage the following code snippet:

<code class="python">x = x[~numpy.isnan(x)]</code>

Explanation:

  • The numpy.isnan() function generates a Boolean array indicating True for NaN values and False otherwise.
  • Using the logical NOT operator ~, we invert the array, resulting in True for non-NaN values.
  • Subsequently, we employ the inverted array as an indexing mask for the original array x.
  • This indexing operation isolates only the elements corresponding to True values, effectively removing NaN values from the array.

The above is the detailed content of How to Exclude NaN Values from NumPy Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn