w3resource

Handling NaN values in NumPy arrays using np.nan_to_num

NumPy: Universal Functions Exercise-17 with Solution

ufunc and NaN Handling:

Write a NumPy program that creates an array with NaN values and uses np.nan_to_num to replace NaN with a specified number.

Sample Solution:

Python Code:

import numpy as np

# Create a NumPy array with NaN values
array_with_nan = np.array([1, 2, np.nan, 4, np.nan, 6])

# Replace NaN values with a specified number, e.g., 0
array_without_nan = np.nan_to_num(array_with_nan, nan=0.0)

# Print the original and modified arrays
print("Original Array with NaN values:")
print(array_with_nan)

print("\nArray after replacing NaN values:")
print(array_without_nan)

Output:

Original Array with NaN values:
[ 1.  2. nan  4. nan  6.]

Array after replacing NaN values:
[1. 2. 0. 4. 0. 6.]

Explanation:

  • Import NumPy Library:
    • Import the NumPy library to handle array operations.
  • Create Array with NaN Values:
    • Define a NumPy array array_with_nan that includes some NaN values.
  • Replace NaN Values:
    • Use "np.nan_to_num()" to replace NaN values in the array with a specified number (e.g., 0.0).
  • Print Original and Modified Arrays:
    • Output both the original array with NaN values and the modified array after replacing NaNs to verify the operation.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: In-Place addition using np.add with the Out parameter in NumPy.
Next: Create a custom ufunc for complex numbers in NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/handling-nan-values-in-numpy-arrays-using-np-dot-nan_to_num.php