检查矩阵/数组的索引,然后检查一些条件

时间:2014-06-30 23:09:06

标签: python numpy

此代码将方阵转换为严格的下三角矩阵(下元素为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]])

有没有办法使用短而甜的地方?

2 个答案:

答案 0 :(得分:1)

它不使用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]])

请注意,您需要将k=-1传递给numpy.tril_indices以不包含对角线。

答案 1 :(得分:0)

找到结果。虽然我正在使用@mdml解决方案。这是点btw。

这只是循环索引以检查行,列条件的正面副作用。也许任何人都可以将它用于其他有意义的目的,其中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 ]])