简体   繁体   English

您可以使用 3 个单独的 1D numpy arrays 来使用矢量化操作 3D 数组吗?

[英]Can you use 3 seperate 1D numpy arrays to manipulate a 3D array using vectorization?

I am trying multiply a specific location of an array by certain value, where the location is determined by the index and the value of the num array.我正在尝试将数组的特定位置乘以某个值,其中位置由索引和 num 数组的值确定。 The certain value comes from the same index position of the multiplier array.该特定值来自乘法器数组的同一索引 position。 We only want to apply this multiplier if the needs_multiplier is value at that index position is true.如果 needs_multiplier 是索引 position 为 true 的值,我们只想应用此乘数。 I think the code will do a better job explaining this.我认为代码会更好地解释这一点。 I am trying to vectorize this and avoid the for loop.我正在尝试对此进行矢量化并避免 for 循环。

import numpy as np

data = np.array([[[ 2.,  2.,  2.,  2.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.]],

                 [[ 1.,  1.,  1.,  1.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.]],

                 [[ 3.,  3.,  3.,  3.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.]],

                 [[ 5.,  5.,  5.,  5.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.],
                  [ 0.,  0.,  0.,  0.]]])

needs_multiplier = np.array([True, True, False, True])
num = np.array([1, 2, 2, 3])
multipler = np.array([0.5, 0.6, 0.2, 0.3])


for i, cfn in enumerate(num):
    if needs_multiplier[i]:
        data[i, 1, cfn] = multipler[i] * data[i, 0, cfn]
        data[i, 2, cfn] = data[i, 0, cfn]-data[i, 1, cfn]

print(data) # this is the result I am looking for

[[[2.  2.  2.  2. ]
  [0.  1.  0.  0. ]
  [0.  1.  0.  0. ]
  [0.  0.  0.  0. ]]

 [[1.  1.  1.  1. ]
  [0.  0.  0.6 0. ]
  [0.  0.  0.4 0. ]
  [0.  0.  0.  0. ]]

 [[3.  3.  3.  3. ]
  [0.  0.  0.  0. ]
  [0.  0.  0.  0. ]
  [0.  0.  0.  0. ]]

 [[5.  5.  5.  5. ]
  [0.  0.  0.  1.5]
  [0.  0.  0.  3.5]
  [0.  0.  0.  0. ]]]

num can be used as index array after selecting "active" values with num[needs_multiplier]在使用num[needs_multiplier]选择“活动”值后, num可以用作索引数组

Then vectorizing the expressions is pretty straight forward:然后向量化表达式非常简单:

b = needs_multiplier
num_b = num[needs_multiplier]

data[b, 1, num_b] = multipler[b] * data[b, 0, num_b]
data[b, 2, num_b] = data[b, 0, num_b] - data[b, 1, num_b]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM