在 2d numpy 数组的每一行中找到最小非零值

我试图在 2d numpy 数组的每一行中找到最小的非零值,但还没有找到一个优雅的解决方案。我看过其他一些帖子,但都没有解决完全相同的问题,例如 Minimum value in 2d arrayMin/Max excluding zeros but in 1d array
例如对于给定的数组:

x = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])

答案是:

[1., 4., 2.]


慕标5832272
浏览 261回答 4
4回答

猛跑小猪

一种方法是将零重新分配给 np.inf,然后每行取最小值:np.where(x>0, x, np.inf).min(axis=1)输出:array([1., 4., 2.])

汪汪一只猫

屏蔽阵列正是为这些目的而设计的。您可以利用数组中的掩码零(或您想要的任何其他类型的掩码),并在您的掩码数组上执行您在常规数组上所做的大部分工作:import numpy.ma as mamx = ma.masked_array(x, mask=x==0)mx.min(1)输出:[1.0 4.0 2.0]

慕少森

# example datax = 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 infinityx[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 npx = np.array([[3., 2., 0., 1., 6.], [8., 4., 5., 0., 6.], [0., 7., 2., 5., 0.]])for i in range(len(x)) :&nbsp; &nbsp; small=x[i][i]&nbsp; &nbsp; for j in x[i] :&nbsp; &nbsp; &nbsp; &nbsp; if (j!=0 and j<small):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; small=j&nbsp; &nbsp; print(small)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python