简体   繁体   中英

Remove Nan occurence/s before first number in Numpy array

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))

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

you could also do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM