如果满足条件,则替换 Numpy 元素 [英] Replacing Numpy elements if condition is met
本文介绍了如果满足条件,则替换 Numpy 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大型 numpy 数组,我需要对其进行操作,以便在满足条件时将每个元素更改为 1 或 0(稍后将用作像素掩码).数组中大约有 800 万个元素,我目前的方法对于减少管道来说花费的时间太长:
for (y,x), numpy.ndenumerate(mask_data) 中的值:如果 mask_data[y,x]<3: #Good Pixelmask_data[y,x]=1elif mask_data[y,x]>3: #Bad Pixelmask_data[y,x]=0
是否有一个 numpy 函数可以加快速度?
解决方案
>>>将 numpy 导入为 np>>>a = np.random.randint(0, 5, size=(5, 4))>>>一种数组([[4, 2, 1, 1],[3, 0, 1, 2],[2, 0, 1, 1],[4, 0, 2, 3],[0, 0, 0, 2]])>>>b = a <3>>>乙数组([[假,真,真,真],[假,真,真,真],[真,真,真,真],[假,真,真,假],[真,真,真,真]],dtype=bool)>>>>>>c = b.astype(int)>>>C数组([[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)I have a large numpy array that I need to manipulate so that each element is changed to either a 1 or 0 if a condition is met (will be used as a pixel mask later). There are about 8 million elements in the array and my current method takes too long for the reduction pipeline:
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
Is there a numpy function that would speed this up?
解决方案
>>> 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]])
You can shorten this with:
>>> c = (a < 3).astype(int)
这篇关于如果满足条件,则替换 Numpy 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文