python 二维数组屏蔽错误
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]])
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]])