Python 二维 numpy 数组中的阈值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36719997/
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-19 18:15:32  来源:igfitidea点击:

threshold in 2D numpy array

pythonnumpy

提问by physics_for_all

I have an array of shape 512x512 which contains numbers between 0 and 100 at ith and jth position. Now I want to select array[i,j] < 25 and zero at other places. I have tried with array = array[where(array<25)], which gives me a 1D array, but I want 2D. Please help me to solve this.

我有一个形状为 512x512 的数组,它在第 i 个和第 j 个位置包含 0 到 100 之间的数字。现在我想在其他地方选择 array[i,j] < 25 和零。我试过array = array[where(array<25)],它给了我一个一维数组,但我想要二维。请帮我解决这个问题。

回答by kazemakase

One solution:

一种解决方案:

result = (array < 25) * array

The first part array < 25gives you an array of the same shape that is 1 (True) where values are less than 25 and 0 (False) otherwise. Element-wise multiplication with the original array retains the values that are smaller than 25 and sets the rest to 0. This does not change the original array

第一部分array < 25为您提供一个形状相同的数组,该数组为 1(真),其中值小于 25,否则为 0(假)。与原始数组的逐元素乘法保留小于 25 的值并将其余值设置为 0。这不会更改原始数组

Another possibility is to set all values that are >= 25 to zero in the original array:

另一种可能性是将原始数组中 >= 25 的所有值设置为零:

array[array >= 25] = 0

回答by hLk

I also wanted to add that you can take advantage of numpy views to achieve this:

我还想补充一点,您可以利用 numpy 视图来实现这一点:

>>> a = np.asarray([ [1,2], [3,4], [4,1], [6,2], [5,3], [0,4] ])
>>> b = a[:, 1] # lets say you only care about the second column
>>> b[b > 3] = 0
>>> print(a)
[[1 2]
 [3 0]
 [4 1]
 [6 2]
 [5 3]
 [0 0]]

This is nice when you want the values to be something other than 0.

当您希望值不是 0 时,这很好。