Home > Backend Development > Python Tutorial > How to Remove NaN (Not-a-Number) Values from a NumPy Array?

How to Remove NaN (Not-a-Number) Values from a NumPy Array?

DDD
Release: 2024-10-18 16:18:30
Original
390 people have browsed it

How to Remove NaN (Not-a-Number) Values from a NumPy Array?

Removing NaN Values from a NumPy Array

NumPy arrays often contain missing or invalid data represented as NaN (Not-a-Number). Removing these values is essential for data manipulation or analysis. Here's how to accomplish this using NumPy:

Using Numpy.isnan and Array Indexing

To remove NaN values from an array x:

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

Explanation:

  1. numpy.isnan(x): This function creates a logical array where True represents NaN values in x.
  2. Logical-NOT Operator (~): The tilde (~) flips the True/False values, resulting in an array with True for non-NaN values.
  3. Array Indexing with the Resulting Array: Using this logical array to index x, we retrieve the elements corresponding to True values, effectively removing the NaN values.

Example:

<code class="python">array = [1, 2, NaN, 4, NaN, 8]

# Remove NaN values
array_cleaned = array[~numpy.isnan(array)]

print(array_cleaned)  # Output: [1, 2, 4, 8]</code>
Copy after login

The above is the detailed content of How to Remove NaN (Not-a-Number) Values from a NumPy Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template