Python 检查矩阵/数组的索引,然后检查某些条件
此代码将方形矩阵转换为严格的下三角矩阵(将下元素转换为0)Python 检查矩阵/数组的索引,然后检查某些条件,python,numpy,Python,Numpy,此代码将方形矩阵转换为严格的下三角矩阵(将下元素转换为0) 有没有办法使用short和sweet where实现这一点?它不使用numpy.where,但可以使用将下三角设置为零: >>> a array([[ 0.05559341, -1.93583316, -1.19666435], [-0.33450047, 0.63275874, 0.77152195], [-0.73106122, -1.57602057, 0.41878224]])
有没有办法使用short和sweet where实现这一点?它不使用
numpy.where
,但可以使用将下三角设置为零:
>>> 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\u索引
,以不包括对角线。找到结果。尽管我准备继续使用@mdml解决方案。顺便说一句,这就是重点
这只是循环索引以检查行、列条件的积极副作用。也许任何人都可以将它用于其他有意义的目的,而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 ]])
@user2290820:是的,再次拯救Numpy:)我不清楚你的问题是不是在问一个修改下三角的简单方法,但我认为这就是你想要知道的全部?最终是的。但我也在谷歌上搜索在numpy w/o中循环索引的方法,以调用循环或快速C API循环。我认为numpy还没有通过索引进行枚举。假设您只想以numpy打印数组的索引。说明其中([i,j]在a是sm条件下,result1,result2);您应该改为使用where(数组)
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 ]])