Python:使用单个值替换数组中的多个切片

时间:2017-11-12 04:52:42

标签: python arrays replace slice

import numpy as np
np.random.seed(5)
x = np.random.randint(0,10,12)
# array([3, 6, 6, 0, 9, 8, 4, 7, 0, 0, 7, 1])

我想要替换几个x子阵列,每个子阵列对应一个值,例如avg。在子阵列上:

# given the start and end indices for THREE subarrays of x
subary_start, subary_end = np.array([0, 2, 8]), np.array([1, 3, 10])
for i, j in zip(subary_start, subary_end):
    val = np.mean(x[i:j+1]) # avg. over the subarray
    print(val)
# 4.5, 3, 2.33

预期的产出是     array([4.5, 3, 9, 8, 4, 7, 2.33, 1])

在我的典型案例中,len(x)可能是一万个,并且可能有数百个切片,因此我们非常感谢有效的解决方案。

1 个答案:

答案 0 :(得分:0)

import copy

def replace_slice(seq, slice_start, slice_end):

    seq = seq.astype(float)
    seq_copy = copy.copy(seq)
    bool_new_seq = np.ones(len(seq_copy), dtype=bool)

    for i, j in zip(slice_start, slice_end):
        bool_new_seq[i+1: j+1] = False
        new_val = np.mean(seq_copy[i: j+1])
        seq_copy[i] = new_val

    new_seq = seq_copy[bool_new_seq]
    return new_seq

replace_slice(x, np.array([0, 2, 8]), np.array([1, 3, 10]))产生预期结果。但是,不确定是否有更好的长序列和切片列表。