Python 计算矩阵中大于某个值的所有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12995937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:22:14  来源:igfitidea点击:

Count all values in a matrix greater than a value

pythonarrayscoding-stylenumpypixel

提问by gran_profaci

I have to count all the values in a matrix (2-d array) that are greater than 200.

我必须计算矩阵(二维数组)中大于 200 的所有值。

The code I wrote down for this is:

我为此写的代码是:

za=0   
p31 = numpy.asarray(o31)   
for i in range(o31.size[0]):   
    for j in range(o32.size[1]):   
        if p31[i,j]<200:   
            za=za+1   
print za

o31is an image and I am converting it into a matrix and then finding the values.

o31是一个图像,我将它转换成一个矩阵,然后找到值。

My question is, is there a simpler way to do this?

我的问题是,有没有更简单的方法来做到这一点?

采纳答案by abought

The numpy.wherefunction is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide.

numpy.where功能是你的朋友。因为它的实现是为了充分利用数组数据类型,所以对于大图像,您应该注意到与您提供的纯 python 解决方案相比速度有所提高。

Using numpy.where directly will yield a boolean mask indicating whether certain values match your conditions:

直接使用 numpy.where 将产生一个布尔掩码,指示某些值是否符合您的条件:

>>> data
array([[1, 8],
       [3, 4]])
>>> numpy.where( data > 3 )
(array([0, 1]), array([1, 1]))

And the mask can be used to index the array directly to get the actual values:

并且掩码可用于直接索引数组以获取实际值:

>>> data[ numpy.where( data > 3 ) ]
array([8, 4])

Exactly where you take it from there will depend on what form you'd like the results in.

您从那里获取它的确切位置将取决于您希望结果的形式。

回答by K Z

There are many ways to achieve this, like flatten-and-filter or simply enumerate, but I think using Boolean/mask arrayis the easiest one (and iirc a much faster one):

有很多方法可以实现这一点,比如展平和过滤或简单地枚举,但我认为使用布尔/掩码数组是最简单的一种(而 iirc 更快):

>>> y = np.array([[123,24123,32432], [234,24,23]])
array([[  123, 24123, 32432],
       [  234,    24,    23]])
>>> b = y > 200
>>> b
array([[False,  True,  True],
       [ True, False, False]], dtype=bool)
>>> y[b]
array([24123, 32432,   234])
>>> len(y[b])
3
>>>> y[b].sum()
56789

Update:

更新

As nneonneo has answered, if all you want is the number of elements that passes threshold, you can simply do:

正如 nneonneo 所回答的那样,如果您想要的只是通过阈值的元素数量,您可以简单地执行以下操作:

>>>> (y>200).sum()
3

which is a simpler solution.

这是一个更简单的解决方案。



Speed comparison with filter:

速度比较filter

### use boolean/mask array ###

b = y > 200

%timeit y[b]
100000 loops, best of 3: 3.31 us per loop

%timeit y[y>200]
100000 loops, best of 3: 7.57 us per loop

### use filter ###

x = y.ravel()
%timeit filter(lambda x:x>200, x)
100000 loops, best of 3: 9.33 us per loop

%timeit np.array(filter(lambda x:x>200, x))
10000 loops, best of 3: 21.7 us per loop

%timeit filter(lambda x:x>200, y.ravel())
100000 loops, best of 3: 11.2 us per loop

%timeit np.array(filter(lambda x:x>200, y.ravel()))
10000 loops, best of 3: 22.9 us per loop

*** use numpy.where ***

nb = np.where(y>200)
%timeit y[nb]
100000 loops, best of 3: 2.42 us per loop

%timeit y[np.where(y>200)]
100000 loops, best of 3: 10.3 us per loop

回答by nneonneo

This is very straightforward with boolean arrays:

这对于布尔数组非常简单:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements

回答by Karol

Here's a variant that uses fancy indexing and has the actual values as an intermediate:

这是一个使用花式索引并将实际值作为中间值的变体:

p31 = numpy.asarray(o31)
values = p31[p31<200]
za = len(values)

回答by Ricoter

To count the number of values larger than x in any numpy array you can use:

要计算任何 numpy 数组中大于 x 的值的数量,您可以使用:

n = len(matrix[matrix > x])

The boolean indexing returns an array that contains only the elements where the condition (matrix > x) is met. Then len() counts these values.

布尔索引返回一个数组,该数组仅包含满足条件 (矩阵 > x) 的元素。然后 len() 计算这些值。