Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract the first occurrence in numpy array following the nan

I have the following array:

[1,1,1,1,1,1,nan,nan,nan,1,1,1,2,2,2,3,3]

I want to extract the first occurrence of 1 in this array following the nan's. I tried this:

numpy.argmax(arr > numpy.nan)
like image 854
user308827 Avatar asked Oct 21 '25 06:10

user308827


1 Answers

np.where(np.isnan(foo))[0][-1] + 1

After the np.where, 0 returns the indices of the elements containing NaN. Then -1 gives you the last NaN index. Then add one to that to find the index of the element after the last NaN.

In your example array, it produces an index of 9

You can then use np.where again to find the first 1 from index 9 onwards.

So altogether:

afternan = np.where(np.isnan(foo))[0][-1] + 1
np.where(foo[afternan:] == 1)[0][0]

Note that your example appears to be a list. I am presuming you transform that to a numpy array.

like image 171
timbo Avatar answered Oct 23 '25 22:10

timbo