[英]check on indices of matrix/array and then check for some condition
This code converts a square matrix to strict lower triangular matrix (lower elements to 0) 此代码将方矩阵转换为严格的下三角矩阵(下元素为0)
a=np.random.randn(9).reshape((3,3))
a
Out[61]:
array([[-0.18314209, 0.3710528 , -1.46067261],
[-0.55834476, -1.41924213, -0.04127718],
[ 0.40134248, -0.41759044, 1.83573994]])
def subs_tri_0(mat,i,j): mat[i,j] = 0
[subs_tri_0(a,i,j) for i,j in product(xrange(a.shape[0]),xrange(a.shape[1])) if i > j]
Out[63]: [None, None, None]
a
Out[64]:
array([[-0.18314209, 0.3710528 , -1.46067261],
[ 0. , -1.41924213, -0.04127718],
[ 0. , 0. , 1.83573994]])
Is there a way to this using short and sweet where? 有没有办法在哪里使用简短而甜蜜的方法呢?
It doesn't use numpy.where
, but you could use numpy.tril_indices
to set the lower triangular to zero: 它不使用
numpy.where
,但是您可以使用numpy.tril_indices
将下部三角形设置为零:
>>> a
array([[ 0.05559341, -1.93583316, -1.19666435],
[-0.33450047, 0.63275874, 0.77152195],
[-0.73106122, -1.57602057, 0.41878224]])
>>> a[np.tril_indices(3, k=-1)] = 0
>>> a
array([[ 0.05559341, -1.93583316, -1.19666435],
[ 0. , 0.63275874, 0.77152195],
[ 0. , 0. , 0.41878224]])
Note that you need to pass k=-1
to numpy.tril_indices
to not include the diagonal. 请注意,您需要将
k=-1
传递给numpy.tril_indices
以不包括对角线。
Found the result. 找到了结果。 Although I'm gona go ahead with @mdml solution.
尽管我要使用@mdml解决方案。 which is to the point btw.
顺便说一句
This is just a positive side effect of looping through indices to check for row,col conditions. 这只是循环遍历索引以检查行,列条件的积极副作用。 perhaps anyone could use it for some other meaningful purpose where tril and triu methods are not the case.
也许任何人都可以将其用于其他有意义的目的,而tril和triu方法不是这种情况。
a=np.random.randn(9).reshape((3,3))
r,c = where(a)
where((r>c).reshape(a.shape),0,a)
Out[169]:
array([[ 1.49230558, 0.6321149 , 0.05299907],
[ 0. , 0.14736346, 0.42516369],
[ 0. , 0. , -0.6878655 ]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.