繁体   English   中英

python 2-d array masking error

[英]python 2-d array masking error

mask = np.tril(np.ones(3, dtype=bool)
print mask
[[ True False False]
 [ True True False]
 [ True True True]]

B = np.zeros(9)
B.shape = (3,3)
print B
[[ 0 0 0 ]
 [ 0 0 0 ]
 [ 0 0 0 ]]

B[mask] 
array([0,0,0,0,0,0])

C = np.array([[1],[0],[0],[1],[0],[1]])

B[mask] = C
ValueError: boolean index array should have 1 dimension

我试图申请.flatten()

B[mask] = C.flatten()
print B
array([[1, 0, 0],
      [0, 0, 0],
      [1, 0, 1]])

但是我的预期结果是对角矩阵。

array([[1, 0, 0],
      [0, 1, 0],
      [0, 0, 1]])

我究竟做错了什么?

您想要np.diag_indices函数,该函数为您提供索引以访问数组的主对角线,而不是tril

In [10]: a = np.zeros((3, 3))

In [11]: indices = np.diag_indices(3)

In [12]: a[indices] = 1

In [13]: a
Out[13]: 
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

问题是您假设列的主要有序值,而NumPy / Python则不是这种情况。 因此,对于使用掩码分配具有列优先顺序值的值的一般情况,我们需要转置输入数组和掩码并分配它们,就像这样-

B.T[mask.T] = C.flatten()

样本运行以获取有关获得正确订单和分配的说明-

In [36]: B = np.arange(1,10).reshape(3,3)

In [37]: B
Out[37]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [38]: mask = np.tril(np.ones(3, dtype=bool))

In [39]: mask
Out[39]: 
array([[ True, False, False],
       [ True,  True, False],
       [ True,  True,  True]])

In [40]: B.T[mask.T] 
Out[40]: array([1, 4, 7, 5, 8, 9]) # right order (col major) obtained

# Finally assign into masked positions
In [41]: B.T[mask.T] = C.flatten()

In [42]: B
Out[42]: 
array([[1, 2, 3],
       [0, 1, 6],
       [0, 0, 1]])

暂无
暂无

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

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