Python 忽略对角线的Numpy数组的最小值
我必须找到忽略对角元素的numpy数组的最大值 amax()提供了忽略特定轴来查找它的方法。忽略所有对角线元素,如何实现相同的效果?这应该可以Python 忽略对角线的Numpy数组的最小值,python,numpy,Python,Numpy,我必须找到忽略对角元素的numpy数组的最大值 amax()提供了忽略特定轴来查找它的方法。忽略所有对角线元素,如何实现相同的效果?这应该可以 >>> import numpy as np >>> import numpy.random # create sample matrix >>> a = numpy.random.randint(10,size=(8,8)) >>> a[0,0] = 100 >>&g
>>> import numpy as np
>>> import numpy.random
# create sample matrix
>>> a = numpy.random.randint(10,size=(8,8))
>>> a[0,0] = 100
>>> a
array([[100, 8, 6, 5, 5, 7, 4, 5],
[4, 6, 1, 7, 4, 5, 8, 5],
[0, 2, 0, 7, 4, 2, 7, 9],
[5, 7, 5, 9, 8, 3, 2, 8],
[2, 1, 3, 4, 0, 7, 8, 1],
[6, 6, 7, 6, 0, 6, 6, 8],
[6, 0, 1, 9, 7, 7, 9, 3],
[0, 5, 5, 5, 1, 5, 4, 4]])
# create mask
>>> mask = np.ones((8,8))
>>> mask = (mask - np.diag(np.ones(8))).astype(np.bool)
>>> mask
array([[False, True, True, True, True, True, True, True],
[ True, False, True, True, True, True, True, True],
[ True, True, False, True, True, True, True, True],
[ True, True, True, False, True, True, True, True],
[ True, True, True, True, False, True, True, True],
[ True, True, True, True, True, False, True, True],
[ True, True, True, True, True, True, False, True],
[ True, True, True, True, True, True, True, False]], dtype=bool)
# calculate the maximum
>>> np.amax(a[mask])
9
你可以用面具
mask = np.ones(a.shape, dtype=bool)
np.fill_diagonal(mask, 0)
max_value = a[mask].max()
其中a
是要查找最大值的矩阵。遮罩选择非对角元素,因此,a[mask]
将是所有非对角元素的长向量。那你就拿max吧
或者,如果您不介意修改原始数组
np.fill_diagonal(a, -np.inf)
max_value = a.max()
当然,您可以复制一份,然后在不修改原件的情况下执行上述操作。此外,这是假设
a
是某种浮点格式。另一种可能性是使用NumPy的作为跨步,将对角线推到第一列,然后将其切掉:
In [1]: import numpy as np
In [2]: from numpy.lib.stride_tricks import as_strided
In [3]: b = np.arange(0,25,1).reshape((5,5))
In [4]: b
Out[4]: array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
In [5]: n = b.shape[0]
In [6]: np.max(as_strided(b, (n-1,n+1), (b.itemsize*(n+1), b.itemsize))[:,1:])
Out[6]: 23
其中np.max
的参数是b
上的移位视图:
In [7]: as_strided(b, (n-1,n+1), (b.itemsize*(n+1), b.itemsize))
Out[7]: array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23]])
以便:
In [8]: as_strided(b, (n-1,n+1), (b.itemsize*(n+1), b.itemsize))[:,1:]
Out[8]: array([[ 1, 2, 3, 4, 5],
[ 7, 8, 9, 10, 11],
[13, 14, 15, 16, 17],
[19, 20, 21, 22, 23]])
哇,太酷了。可能比在大型数组中使用掩码更快。这可以扩展到批处理矩阵(即,在前面有一些维度的情况下)?@user76284这可能适用于m
n
xn
数组:np.max(如跨步(c,(m,n-1,n+1),(c.itemsize*n*n,c.itemsize*(n+1),c.itemsize)][:,1:],axis=(1,2))
:为了得到更好的答案,我认为你应该问一个新问题。[mask].max()和np.max(a[mask])之间有什么区别?@Gerald我不知道有什么区别。你也可以只使用a[~np.eye(*a.shape,dtype=bool)].max()
。