python 2-d数组掩码错误

时间:2018-04-13 10:29:28

标签: python arrays numpy mask masking

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]])

我做错了什么?

2 个答案:

答案 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.]])

答案 1 :(得分:0)

问题是你假设是列主要有序值,而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]])