1

I have an array (arr) with random NaNs and numbers.

arr = np.array((np.nan, np.nan, 2.3, np.nan, np.nan, 6.4, np.nan))

I need to check and remove, if present, Nan occurence/s before first number in index, here below the result:

result = np.array((2.3, np.nan, np.nan, 6.4, np.nan))
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Tom
  • 132
  • 7

2 Answers2

0

Similar to the solution here, you can find the first non nan value, then slice your array from this index onwards. Easy to use the numpy.where method, similar to how they use it in this answer This should work:

arr[np.where( np.isnan(arr)==False)[0][0]:]

of course if you want to actually override the old array you can do:

arr = arr[np.where( np.isnan(arr)==False)[0][0]:]

and in the example:

import numpy as np
arr = np.array((np.nan, np.nan, 2.3, np.nan, np.nan, 6.4, np.nan))
result = arr[np.where( np.isnan(arr)==False)[0][0]:]

has [2.3 nan nan 6.4 nan] in result

Or b
  • 666
  • 1
  • 5
  • 22
0

you could also do something like:

import math
for i,x in enumerate(arr):
    if not math.isnan(x):
        break
arr = arr[i:]
Bennimi
  • 416
  • 5
  • 14