【问题标题】:How to transform an ndarray by an index mapping如何通过索引映射转换 ndarray
【发布时间】:2022-10-06 04:48:20
【问题描述】:

如何通过索引映射转换 ndarray?例如,

>>> import numpy as np
>>> x = np.arange(3*4).reshape((3,4))
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> wanted = np.array([[x[i, 1+i-2*j] if 1+i-2*j>=0 and 1+i-2*j<4 else 0 for j in range(4)] for i in range(3)])
>>> wanted
array([[ 1,  0,  0,  0],
       [ 6,  4,  0,  0],
       [11,  9,  0,  0]])

我们可以用矢量化的方式(不是循环或列表印象)吗?在我相当大的 ndarray 上,列表压缩或循环非常慢。

    标签: python numpy-ndarray


    【解决方案1】:

    您可以通过一些简单的索引技巧来避免循环(因此也可以避免列表理解)。
    以下代码 sn-p 的口头描述是:

    1. 定义列和行矩阵
    2. 计算二进制“条件”矩阵
    3. 定义所需的线性组合索引
    4. 结合使用索引和条件来计算最终输出

      在代码中 -

      import numpy as np
      
      x = np.arange(3*4).reshape((3,4))
      c_ = np.tile(np.arange(4), (3, 1))  # Step 1
      r_ = np.tile(np.arange(3).reshape(3, 1), (1, 4))  # Step 1
      condition = np.logical_and(1 + r_ - 2 * c_ >= 0, 1 + r_ - 2 * c_ < 4)  # Step 2
      wanted = x[r_, (1 + r_ - 2 * c_) * condition] * condition  # Steps 3 and 4
      print(wanted)
      # [[ 1  0  0  0]
      # [ 6  4  0  0]
      # [11  9  0  0]]
      

      (请注意,在索引x 时,您需要将列 index-matrix 乘以condition,以便线性组合不会溢出x.shape。无关紧要的值全部取自列0,因为无论如何我们都将这些位置的输出归零)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 2019-07-28
      • 2010-12-23
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 2012-04-09
      相关资源
      最近更新 更多