存在多个条件时替换numpy数组中的元素 [英] Replacing elements in a numpy array when there are multiple conditions
问题描述
此问题与以下帖子相关:如果条件为,则替换Numpy元素遇见.
This question is related to the following post: Replacing Numpy elements if condition is met.
假设我有两个一维的numpy数组a
和b
,每个数组有50行.
Suppose i have two, one-dimensional numpy arrays a
and b
, with 50 rows each.
我想创建一个包含50行的数组c
,每行将根据是否满足条件采用0-4的值:
I would like to create an array c
of 50 rows, each of which will take the values 0-4 depending on whether a condition is met:
if a > 0 the value in the corresponding row of c should be 0
if a < 0 the value in the corresponding row of c should be 1
if a > 0 and b < 0 the value in the corresponding row of c should be 2
if b > 0 the value in the corresponding row of c should be 3
我想这是一个更广泛的问题,我如何才能将特定的值分配给 有多个条件时的数组.我已经尝试了上面提到的帖子的各种变体,但没有成功.
I suppose the broader question here is how can i assign specific values to an array when there are multiple conditions. I have tried variations from the post i referenced above but i have not been successful.
关于如何实现此目标的任何想法,最好不使用 for循环?
Any ideas of how i could achieve this, preferably without using a for-loop?
推荐答案
直接解决方案是按顺序应用分配.
A straight forward solution would be to apply the assignments in sequence.
In [18]: a = np.random.choice([-1,1],size=(10,))
In [19]: b = np.random.choice([-1,1],size=(10,))
In [20]: a
Out[20]: array([-1, 1, -1, -1, 1, -1, -1, 1, 1, -1])
In [21]: b
Out[21]: array([-1, 1, 1, 1, -1, 1, -1, 1, 1, 1])
从具有默认值的数组开始:
Start off with an array with the 'default' value:
In [22]: c = np.zeros_like(a)
应用第二个条件:
In [23]: c[a<0] = 1
第三个需要注意一点,因为它结合了两个测试. ()很重要:
The third requires a little care since it combines 2 tests. () matter here:
In [25]: c[(a>0)&(b<0)] = 2
最后一个:
In [26]: c[b>0] = 3
In [27]: c
Out[27]: array([1, 3, 3, 3, 2, 3, 1, 3, 3, 3])
看起来所有开头的0都被覆盖了.
Looks like all of the initial 0s are overwritten.
在数组中有许多元素,仅进行了几次测试,我就不必担心速度.专注于清晰度和表现力,而不是紧凑性.
With many elements in the arrays, and just a few tests, I wouldn't worry about speed. Focus on clarity and expressiveness, not compactness.
where
有3个参数的版本,可以在值或数组之间进行选择.但是我很少使用它,也没有看到很多关于它的问题.
There is a 3 argument version of where
that can choose between values or arrays. But I rarely use it, and don't see many questions about it either.
In [28]: c = np.where(a>0, 0, 1)
In [29]: c
Out[29]: array([1, 0, 1, 1, 0, 1, 1, 0, 0, 1])
In [30]: c = np.where((a>0)&(b<0), 2, c)
In [31]: c
Out[31]: array([1, 0, 1, 1, 2, 1, 1, 0, 0, 1])
In [32]: c = np.where(b>0, 3, c)
In [33]: c
Out[33]: array([1, 3, 3, 3, 2, 3, 1, 3, 3, 3])
这些where
可以链接在一行上.
These where
s could be chained on one line.
c = np.where(b>0, 3, np.where((a>0)&(b<0), 2, np.where(a>0, 0, 1)))
这篇关于存在多个条件时替换numpy数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!