user308827
user308827

Reputation: 21981

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)

Upvotes: 4

Views: 8410

Answers (1)

timbo
timbo

Reputation: 14334

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.

Upvotes: 6

Related Questions