二维 numpy 数组的条件数学运算检查一维并在差异维度上执行不同的操作

Conditional maths operation on 2D numpy array checking on one dimension and doing different operations on diff dimensions

我有一个 2D numpy 数组,其中第 0 列是设备的平移旋转,第 1 列是倾斜旋转。每一行都是不同的夹具。我想 运行 每行的以下逻辑:

if(pantilt[0] > 90):
    pantilt[0] -=180
    pantilt[1] *= -1
elif pantilt[0] < -90:
    pantilt[0] += 180
    pantilt[1] *= -1

我了解 1D 上的基本条件运算,例如 myarray[condition] = something。但我无法将其外推到更多维度。

这个怎么样:

pantilt[:,0][pantilt[:,0]>90] -= 180
pantilt[:,1][pantilt[:,0]>90] *= -1
pantilt[:,0][pantilt[:,0]<-90] += 180
pantilt[:,1][pantilt[:,0]<-90] *= -1

我会计算掩码或布尔索引,并对每一列使用 if:

构建示例数组:

pantilt=np.column_stack([np.linspace(-180,180,11),np.linspace(0,90,11)])

I = pantilt[:,0]>90
# J = pantilt[:,0]<-90 
pantilt[I,0] -= 180
pantilt[I,1] *= -1

I = pantilt[:,0]<-90  # could use J instead
pantilt[I,0] += 180
pantilt[I,1] *= -1

之前:

array([[-180.,    0.],
       [-144.,    9.],
       [-108.,   18.],
       [ -72.,   27.],
       [ -36.,   36.],
       [   0.,   45.],
       [  36.,   54.],
       [  72.,   63.],
       [ 108.,   72.],
       [ 144.,   81.],
       [ 180.,   90.]])

之后:

array([[  0.,  -0.],
       [ 36.,  -9.],
       [ 72., -18.],
       [-72.,  27.],
       [-36.,  36.],
       [  0.,  45.],
       [ 36.,  54.],
       [ 72.,  63.],
       [-72., -72.],
       [-36., -81.],
       [  0., -90.]])

如果列是单独的一维数组,这也同样有效。

, one can use masking的启发,分为三步,而不是其他两个解决方案中提出的四步,就像这样-

import numpy as np

# Get mask correspindig to IF conditional statements in original code
mask_lt = pantilt[:,0]<-90
mask_gt = pantilt[:,0]>90

# Edit the first column as per the statements in original code
pantilt[:,0][mask_gt] -= 180
pantilt[:,0][mask_lt] += 180

# Edit the second column as per the statements in original code
pantilt[ mask_lt | mask_gt,1] *= -1

运行时测试

用于比较目前列出的三种方法的快速运行时测试 -

In [530]: num_samples = 10000
     ...: org = np.random.randint(-180,180,(num_samples,2))
     ...: 

In [531]: pantilt = org.copy()

In [532]: %timeit hpaulj_mask4(pantilt)
10000 loops, best of 3: 27.7 µs per loop

In [533]: pantilt = org.copy()

In [534]: %timeit maxymoo_mask4(pantilt)
10000 loops, best of 3: 33.7 µs per loop

In [535]: pantilt = org.copy()

In [536]: %timeit mask3(pantilt) # three-step masking approach from this solution
10000 loops, best of 3: 22.1 µs per loop