【问题标题】:Repeating numpy array elements according to another index array根据另一个索引数组重复numpy数组元素
【发布时间】:2018-02-19 08:42:28
【问题描述】:

我有以下占位符数组:

placeholder = np.zeros(10)

A 包含我要进入占位符的值

A = np.array([25, 40, 65,50])

idx 具有占位符的索引(请注意,这与A 具有相同的形状)

idx = np.array([0, 5, 6, 8])

问题:

我希望用A 的元素填充placeholder。 A 中的元素要重复的数量由idx 数组的间隔长度定义。

例如 25 重复 5 次,因为对应的索引范围是 [0, 5)。 65重复两次,因为对应的索引范围是[6,8)

预期输出:

np.array([25, 25, 25, 25, 25, 40, 65, 65, 50, 50])

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    使用np.diff + np.repeat 快速简单:

    repeats = np.diff(np.append(idx, len(placeholder)))
    
    A.repeat(repeats)
    array([25, 25, 25, 25, 25, 40, 65, 65, 50, 50])
    

    【讨论】:

      【解决方案2】:

      如果要使用placeholder数组:

      import numpy as np
      
      placeholder = np.zeros(10)
      A = np.array([25, 40, 65,50])
      idx = np.array([0, 5, 6, 8])
      
      placeholder[idx[0]] = A[0]
      placeholder[idx[1:]] = np.diff(A)    
      np.cumsum(placeholder, out=placeholder)
      

      【讨论】:

      • 这个解决方案太棒了!不幸的是,我不得不接受另一个,因为它的可读性。
      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 2018-10-25
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      相关资源
      最近更新 更多