简体   繁体   English

如何在连续值块之间替换值

[英]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 .所以在这个列表中有连续值的块,由NaN分隔。

How can I replace the values before the maximum of each block, for example with -1.如何替换每个块的最大值之前的值,例如用-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:由于最大值只是最后一个非 NaN 值,因此您可以通过检查给定值是否不是NaN并且以下值也不是,来获取要设置为-1的值的索引:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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