Home  >  Article  >  Backend Development  >  How to Remove NaN Values from NumPy Arrays?

How to Remove NaN Values from NumPy Arrays?

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

How to Remove NaN Values from NumPy Arrays?

Removing NaN Values from NumPy Arrays

When dealing with numerical data in NumPy arrays, it's often encountered to have missing values represented by NaN (Not-a-Number). To ensure proper data analysis and avoid errors, it becomes necessary to remove these NaN values. This article presents the solution for effectively removing NaNs from NumPy arrays.

Method:

NumPy provides a straightforward method to remove NaN values using:

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

Explanation:

The core of this solution lies in the NumPy function numpy.isnan. This function takes an input array and returns a boolean array of the same shape, where True corresponds to NaN values, and False to valid numerical values.

To remove the NaN values, the logical negation operator ~ is applied to the boolean array. This results in an array where True is where valid numbers reside, and False where NaNs are present.

Finally, subscripting the original array x with the boolean array filters out the elements where the value is False (i.e., NaN). This effectively removes all NaN values from the array, resulting in an array with only valid numbers.

The above is the detailed content of How to Remove 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