gpt4 book ai didi

python - 如果满足条件,则替换 Numpy 元素

转载 作者:IT老高 更新时间:2023-10-28 21:42:55 26 4
gpt4 key购买 nike

我有一个大型 numpy 数组,我需要对其进行操作,以便在满足条件时将每个元素更改为 1 或 0(稍后将用作像素掩码)。数组中大约有 800 万个元素,我当前的方法对于缩减管道而言耗时太长:

for (y,x), value in numpy.ndenumerate(mask_data): 

if mask_data[y,x]<3: #Good Pixel
mask_data[y,x]=1
elif mask_data[y,x]>3: #Bad Pixel
mask_data[y,x]=0

有没有一个 numpy 函数可以加快这个速度?

最佳答案

>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
[3, 0, 1, 2],
[2, 0, 1, 1],
[4, 0, 2, 3],
[0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False, True, True, True],
[False, True, True, True],
[ True, True, True, True],
[False, True, True, False],
[ True, True, True, True]], dtype=bool)
>>>
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]])

您可以通过以下方式缩短它:

>>> c = (a < 3).astype(int)

关于python - 如果满足条件,则替换 Numpy 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19766757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com