【问题标题】:Python: replace several slices in an array with single valuesPython:用单个值替换数组中的多个切片
【发布时间】:2017-11-12 04:52:41
【问题描述】:
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) 可以是一万个,并且可以有数百个切片,因此非常感谢一个有效的解决方案。

【问题讨论】:

  • 您的解决方案有效吗?
  • np.mean() 已经以最有效的方式实现。
  • 切片的开始和索引是否总是包含在单独的 ndarray 中?
  • @wwii 是的,它可以工作,但有点愚蠢:创建一个与x 长度相同的True ary,将切片的索引设置为False,同时保留True 作为起始索引。使用布尔数组索引x,并将起始索引设置为相应的替换值。
  • @wwii 我将subary_startsubend_end 与另一个函数一起推导出来,我认为它们的格式可以不受这种方式的限制。

标签: python arrays replace slice


【解决方案1】:
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])) 产生预期的结果。但是,不确定对于长序列和切片列表是否有更好的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2018-11-11
    • 2022-01-03
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    相关资源
    最近更新 更多