Reputation: 851
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]
Upvotes: 0
Views: 86
Reputation: 88266
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])
Upvotes: 1
Reputation: 452
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]
Upvotes: 0