使用numpy函数可能有更好的方法来执行此操作,但这是使用
itertools module的解决方案:
from itertools import groupby
for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
if k:
indices = list(g)
new_v = (this_array[indices[0]-1] + this_array[indices[-1]+1]) / 2
this_array[indices[0]:indices[-1]+1].fill(new_v)
如果最后一个元素或第一个元素可以是9999,则使用以下内容:
from itertools import groupby
for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
if k:
indices = list(g)
prev_i, next_i = indices[0]-1, indices[-1]+1
before = this_array[prev_i] if prev_i != -1 else this_array[next_i]
after = this_array[next_i] if next_i != len(this_array) else before
this_array[indices[0]:next_i].fill((before + after) / 2)
使用第二版的示例:
>>> from itertools import groupby
>>> this_array = np.array([9999, 4, 1, 9999, 9999, 9999, -5, -4, 9999])
>>> for k, g in groupby(range(len(this_array)), lambda i: this_array[i] == 9999):
... if k:
... indices = list(g)
... prev_i, next_i = indices[0]-1, indices[-1]+1
... before = this_array[prev_i] if prev_i != -1 else this_array[next_i]
... after = this_array[next_i] if next_i != len(this_array) else before
... this_array[indices[0]:next_i].fill((before + after) / 2)
...
>>> this_array
array([ 4, 4, 1, -2, -2, -2, -5, -4, -4])