Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

numpy.isnan() in Python

In your Python journey with numpy arrays, there will come a time when you will need to determine whether an array contains any NaN (not a number) values. In this blog post, we'll explore the numpy.isnan() function that serves precisely this need.

Let's consider a simple example to understand the numpy.isnan() function. Suppose we have an array "a" as follows where we deliberately introduce a NaN using the numpy.nan constant.

In numpy, the gradient function takes an array of values as input and computes the numerical gradient along a specified axis. The resulting gradient array has the same shape as the input array.

import numpy as np

a = np.array([1, 2, np.nan, 3, 4])

print(np.isnan(a))

Only the third element is an NaN, so the output is:

[False False  True False False]

The numpy.isnan() function is useful in a variety of scenarios. For instance, you can use it to check if an array contains any NaN values before performing mathematical operations on the array. Or, you could use it to help replace NaN values with a specified value using the numpy.nan_to_num() function. Yet another use is to create masks for arrays to ignore NaN values during computations.

Here is a second example where we are testing if specific elements are NaN:

Python numpy.isnan()

import numpy as np

a = np.array([np.log(1),np.inf, np.pi, np.e])
print(a)
print(np.isnan(a))

As you can expect all elements of the array are specific values and thus none of them are NaNs. The output is:

[0. inf 3.14159265 2.71828183]
[False False False False]

Note that “inf” (denoting infinity) does not evaluate to an NaN.

In summary, the numpy.isnan() function is a useful tool in Python numpy that allows us to quickly check if an array contains any NaN values. It is a simple yet powerful function that can be used in a variety of scenarios, making it a must-have tool in any data analyst or scientist's toolkit.

If you liked learning about numpy.isnan(), learn about numpy.any() which is one way to see if “any” of the values in a numpy array satisfy a condition (such as the isnan() condition).

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.