简体   繁体   中英

How to replace values among blocks of consecutive values

I have a list like this:

list_tmp = [np.NaN, np.NaN, 1, 2, 3, np.NaN, 1, 2, np.NaN, np.NaN, 1, 2, 3, 4, np.NaN]

So in this list there are blocks of consecutive values, separated by NaN .

How can I replace the values before the maximum of each block, for example with -1. The result looks like:

list_tmp = [np.NaN, np.NaN, -1, -1, 3, np.NaN, -1, 2, np.NaN, np.NaN, -1, -1, -1, 4, np.NaN]

Since the maximum value is just the last non-NaN value, you can obtain the indices of the values to set to -1 by checking if a given value is not a NaN and neither is the following:

a = np.array([np.NaN, np.NaN, 1, 2, 3, np.NaN, 1, 2, np.NaN, np.NaN, 1, 2, 3, 4, np.NaN])

a[~np.isnan(a) & ~np.isnan(np.r_[a[1:],np.nan])] = -1

print(a)
array([nan, nan, -1., -1.,  3., nan, -1.,  2., nan, nan, -1., -1., -1., 4., nan])
list_tmp = [np.NaN, np.NaN, 1, 2, 3, np.NaN, 1, 2, np.NaN, np.NaN, 1, 2, 3, 4, np.NaN]

for i in range(len(list_tmp)-1):
  if np.isnan(list_tmp[i])==False and np.isnan(list_tmp[i+1])==False:
    list_tmp[i] =-1

list_tmp

[nan, nan, -1, -1, 3, nan, -1, 2, nan, nan, -1, -1, -1, 4, nan]

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