为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕标5832272 2023-04-18 16:33:59
我试图在 2d numpy 数组的每一行中找到最小的非零值,但还没有找到一个优雅的解决方案。我看过其他一些帖子,但都没有解决完全相同的问题,例如 Minimum value in 2d array或Min/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.]
查看完整描述

4 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

一种方法是将零重新分配给 np.inf,然后每行取最小值:

np.where(x>0, x, np.inf).min(axis=1)

输出:

array([1., 4., 2.])


查看完整回答
反对 回复 2023-04-18
?
汪汪一只猫

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]


查看完整回答
反对 回复 2023-04-18
?
慕少森

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)


查看完整回答
反对 回复 2023-04-18
?
蓝山帝景

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)


查看完整回答
反对 回复 2023-04-18
  • 4 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信