2

I have a numpy array that contains nan and I want to extract only the finite values to get a subarray but without using a loop.

For example:

import numpy as np

z = np.array([2, 3, np.nan, 5])

And I would like to use an instruction such as:

z_cut = z[z != np.nan]

but this doesn't work as it is not possible to compare nan this way.

I could use a loop with instructions such as np.isnan or np.isfinite to get the subarray I want, but I was wondering if there was a more efficient way to do it ?

2
  • Does this answer your question? How can I remove Nan from list Python/NumPy Commented Jul 21, 2020 at 23:47
  • It is a bit different from my post as the "nan" in the post you shared is not actually NaN value but a string. The accepted answer is closer to what I expected but thank you. Commented Jul 21, 2020 at 23:54

1 Answer 1

2

Use ~ operator and np.isnan function

In [23]: import numpy as np
    ...:
    ...: z = np.array([2, 3, np.nan, 5])

In [24]: z[~np.isnan(z)]
Out[24]: array([2., 3., 5.])

In [25]: z_cut = z[~np.isnan(z)]

In [26]: z_cut
Out[26]: array([2., 3., 5.])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.