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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics