替换 Python NumPy 数组中大于某个值的所有元素 [英] Replace all elements of Python NumPy Array that are greater than some value
问题描述
我有一个 2D NumPy 数组,我想用 255.0.0 替换其中大于或等于阈值 T 的所有值.据我所知,最基本的方法是:
I have a 2D NumPy array and would like to replace all values in it greater than or equal to a threshold T with 255.0. To my knowledge, the most fundamental way would be:
shape = arr.shape
result = np.zeros(shape)
for x in range(0, shape[0]):
for y in range(0, shape[1]):
if arr[x, y] >= T:
result[x, y] = 255
最简洁和 Pythonic 的方法是什么?
What is the most concise and pythonic way to do this?
有没有更快(可能不那么简洁和/或不那么 Pythonic)的方法来做到这一点?
Is there a faster (possibly less concise and/or less pythonic) way to do this?
这将是用于人体头部 MRI 扫描的窗口/水平调整子程序的一部分.二维 numpy 数组是图像像素数据.
This will be part of a window/level adjustment subroutine for MRI scans of the human head. The 2D numpy array is the image pixel data.
推荐答案
我认为最快和最简洁的方法是使用 NumPy 的内置 Fancy 索引.如果您有一个名为 arr
的 ndarray
,则可以将所有元素 >255
替换为值 x
,如下所示:
I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray
named arr
, you can replace all elements >255
with a value x
as follows:
arr[arr > 255] = x
我在我的机器上用一个 500 x 500 的随机矩阵运行它,用 5 替换所有 >0.5 的值,平均耗时 7.59 毫秒.
I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.
In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop
这篇关于替换 Python NumPy 数组中大于某个值的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!