How to Count the Number of NaN Values in a 2D Array in Python?

Estimated read time 1 min read

To count the number of NaN (Not a Number) values in a 2D array in Python, you can use the NumPy library, which provides efficient array operations. Here’s an example:

import numpy as np

# Create a 2D array with NaN values
arr = np.array([[1.0, np.nan, 3.0],
                [np.nan, 5.0, 6.0],
                [7.0, 8.0, np.nan]])

# Count NaN values in the array
nan_count = np.isnan(arr).sum()

# Print the count of NaN values
print(f"Number of NaN values: {nan_count}")

In this example, we first create a 2D NumPy array arr with some NaN values. Then, we use the np.isnan() function to create a boolean mask where True values indicate the presence of NaN values in the array. Finally, we use the sum() method on the boolean mask to count the number of True values, which represents the count of NaN values in the array. The result is printed using the print() statement.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply