python数组中元素替换_Python:替换数组中的值

使用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])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值