首页 > 解决方案 > 在二维数组中查找大于 0 的最小值。Python

问题描述

我试图在大于 0 的 2D 数组中找到最小值。我查看了针对 1D 情况给出的解决方案,并试图将其应用于这种特殊情况,但我什么也没得到。

count1
Out[36]: 
array([[2787, 2748, 2752, ..., 2820, 2832, 2903],
       [2794, 2729, 2748, ..., 2810, 2811, 2872],
       [2785, 2796, 2773, ..., 2852, 2877, 2854],
       ...,
       [2833, 2713, 2692, ..., 2703, 2883, 2974],
       [2759, 2726, 2688, ..., 2779, 2863, 2893],
       [2802, 2755, 2637, ..., 2777, 2841, 2946]], dtype=uint16)

k =0

a = np.min(filter(lambda x: x>k,count1))

a
Out[39]: <filter at 0x1a56f9dbc88>

由于我不知道的原因,我没有得到实际值,而是得到了过滤器消息。任何帮助,将不胜感激。

标签: pythonarrays

解决方案


filter返回一个可迭代的。您需要遍历可迭代对象以获取值。这会起作用:

filtered = [f for f in filter(lambda x: x > 0, count1)]
a = np.min(filtered)

或者一个更好的主意是在 numpy 中使用布尔索引。例如,

filter = count1 > 0
filtered = count1[filter]
a = np.min(filtered)

或者您可以将它们组合成一个语句

a = np.min(count1[count1 > 0])

推荐阅读