python-scipyHow do I use Python Numpy to work with NaN values?
Python Numpy provides various functions to work with NaN values.
np.nan_to_num()
: This function replaces NaN values with zero and Infinity values with finite numbers.
Example
import numpy as np
arr = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
print("Original array:")
print(arr)
temp = np.nan_to_num(arr)
print("\nAfter replacing NaN with zero:")
print(temp)
Output example
Original array:
[nan 1. 2. nan 3. 4. 5.]
After replacing NaN with zero:
[0. 1. 2. 0. 3. 4. 5.]
np.isnan()
: This function returns a boolean array of True and False values, where True corresponds to NaN values and False corresponds to non-NaN values.
Example
import numpy as np
arr = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
print("Original array:")
print(arr)
temp = np.isnan(arr)
print("\nBoolean array:")
print(temp)
Output example
Original array:
[nan 1. 2. nan 3. 4. 5.]
Boolean array:
[ True False False True False False False]
np.where()
: This function returns indices of elements that satisfy a certain condition.
Example
import numpy as np
arr = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
print("Original array:")
print(arr)
temp = np.where(np.isnan(arr))
print("\nIndices of elements with value NaN:")
print(temp)
Output example
Original array:
[nan 1. 2. nan 3. 4. 5.]
Indices of elements with value NaN:
(array([0, 3]),)
np.fillna()
: This function is used to fill NaN values with some specified values.
Example
import numpy as np
arr = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
print("Original array:")
print(arr)
temp = np.fillna(arr, 0)
print("\nAfter replacing NaN with 0:")
print(temp)
Output example
Original array:
[nan 1. 2. nan 3. 4. 5.]
After replacing NaN with 0:
[0. 1. 2. 0. 3. 4. 5.]
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Python Scipy to fit a curve?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I integrate Scipy with Python?
- How can I use Python and Numpy to parse XML data?
- How do I create a numpy array of zeros using Python?
- How can I use RK45 with Python and SciPy?
- How do I use Scipy zeros in Python?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
See more codes...