Numpy Array忽略对角线的最小值 [英] Minimum of Numpy Array Ignoring Diagonal

查看:174
本文介绍了Numpy Array忽略对角线的最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须忽略对角线元素而找到一个numpy数组的最大值.

I have to find the maximum value of a numpy array ignoring the diagonal elements.

np.amax()提供了忽略特定轴来查找它的方法.忽略所有对角线元素,如何实现相同的效果?

np.amax() provides ways to find it ignoring specific axes. How can I achieve the same ignoring all the diagonal elements?

推荐答案

您可以使用面具

mask = np.ones(a.shape, dtype=bool)
np.fill_diagonal(mask, 0)
max_value = a[mask].max()

其中,a是要查找最大值的矩阵.遮罩会选择非对角线元素,因此a[mask]将是所有非对角线元素的长向量.然后,您就拿最大的.

where a is the matrix you want to find the max of. The mask selects the off-diagonal elements, so a[mask] will be a long vector of all the off-diagonal elements. Then you just take the max.

或者,如果您不介意修改原始数组

Or, if you don't mind modifying the original array

np.fill_diagonal(a, -np.inf)
max_value = a.max()

当然,您始终可以进行复制,然后执行上述操作而无需修改原始文档.另外,这是假设a是某种浮点格式.

Of course, you can always make a copy and then do the above without modifying the original. Also, this is assuming that a is some floating point format.

这篇关于Numpy Array忽略对角线的最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆