我试图寻找2D numpy数组中每行最小的非零值,但是一直没有找到优雅的解决方案。 我查看了一些其他帖子,但没有一个解决完全相同的问题,例如在2D数组中找到最小值或在1D数组中排除零的最小/最大值。
例如给定以下数组:x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])
答案如下:
[1., 4., 2.]
我试图寻找2D numpy数组中每行最小的非零值,但是一直没有找到优雅的解决方案。 我查看了一些其他帖子,但没有一个解决完全相同的问题,例如在2D数组中找到最小值或在1D数组中排除零的最小/最大值。
例如给定以下数组:x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])
[1., 4., 2.]
np.where(x>0, x, np.inf).min(axis=1)
输出:
array([1., 4., 2.])
x
仍然完好无损。 - Joe Ferndz遮盖数组正是为此类目的而设计的。您可以利用从数组中屏蔽掉的零(或任何其他类型的掩码),并且现在可以对您的遮盖数组执行几乎所有正常数组上的操作:
import numpy.ma as ma
mx = ma.masked_array(x, mask=x==0)
mx.min(1)
输出:
[1.0 4.0 2.0]
# example data
x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])
# set all the values inside the maxtrix which are equal to 0, to *inf*
# np.inf represents a very large number
# inf, stands for infinity
x[x==0] = np.inf
# grep the lowest value, in each array (now that there is no 0 value anymore)
np.min(x, axis=1)
我用的解决方法时间复杂度为o(n^2)
。
import numpy as np
x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])
for i in range(len(x)) :
small=x[i][i]
for j in x[i] :
if (j!=0 and j<small):
small=j
print(small)