简体   繁体   English

如何使用布尔掩码混合两个numpy数组,以有效地创建一个相同的大小?

[英]How to mix two numpy arrays using a boolean mask to create one of the same size efficiently?

I use two arrays of the same size like : 我使用两个相同大小的数组,如:

>>> a = [range(10)]
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = -a
>>> b
array([ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9])

I want to create another array using a boolean "mask", for example : 我想使用布尔“掩码”创建另一个数组,例如:

>>> m = (a % 2 == 0)
>>> m
array([ True, False,  True, False,  True, False,  True, False,  True, False], dtype=bool)

Then I create a third array of the same size and change its values for the ones of a if m is True and for the ones of b if m is False : 然后我创建一个相同大小的第三个数组,并更改其值为if m为True的值,如果m为False则更改为b的值:

>>> c = ones(10)
>>> c[m] = a[m]
>>> c[~m] = b[~m]
>>> c
array([ 0., -1.,  2., -3.,  4., -5.,  6., -7.,  8., -9.])

I wonder if there is a way to do the three last operations (the creation of c) within just one operation (especially for performance optimisation). 我想知道是否有办法在一次操作中完成最后三次操作(创建c)(特别是对于性能优化)。

The problem of doing : 做的问题:

c = a * m + b * m c = a * m + b * m

is when there are NaN in a or b, when it is multiplied by zero it still makes NaN. 是当a或b中有NaN时,当它乘以零时,它仍会产生NaN。

PS : The example I gave would also work for n-dimensionnal arrays. PS:我给出的例子也适用于n维数组。

You are looking for numpy.where : 您正在寻找numpy.where

c = numpy.where(m, a, b)

Good luck. 祝好运。

Using list comprehension you could create some conditionals that determine what list to pick form? 使用列表推导,您可以创建一些条件来确定要选择哪个列表?

result = [ a[i] if bol else b[i] for i, bol in enumerate(mask)]

And then you could apply some functions to a[i] or b[i] depending on how you want to alter them. 然后你可以根据你想要改变它们的方式将一些函数应用到[i]或b [i]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM