4 回答
TA贡献1858条经验 获得超8个赞
一种方法是将零重新分配给 np.inf,然后每行取最小值:
np.where(x>0, x, np.inf).min(axis=1)
输出:
array([1., 4., 2.])
TA贡献1898条经验 获得超8个赞
屏蔽阵列正是为这些目的而设计的。您可以利用数组中的掩码零(或您想要的任何其他类型的掩码),并在您的掩码数组上执行您在常规数组上所做的大部分工作:
import numpy.ma as ma
mx = ma.masked_array(x, mask=x==0)
mx.min(1)
输出:
[1.0 4.0 2.0]
TA贡献2019条经验 获得超9个赞
# 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)
TA贡献1843条经验 获得超7个赞
我用这种方式解决了,时间复杂度是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)
添加回答
举报