当存在多个条件时替换numpy数组中的元素

2024-06-06 16:08:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题与以下帖子有关:Replacing Numpy elements if condition is met。在

假设我有两个一维numpy数组a和{},每个数组有50行。在

我想创建一个由50行组成的数组c,每个行的值都是0-4,这取决于是否满足某个条件:

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

我想这里更广泛的问题是如何为 当有多个条件时数组。我试过与我上面提到的帖子不同的地方,但是我没有成功。在

有什么想法我可以做到这一点,最好不用 for循环?在


Tags: oftheinnumpyifvalue数组elements
3条回答

一个直接的解决方案是按顺序应用分配。在

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])

从具有“default”值的数组开始:

^{pr2}$

应用第二个条件:

In [23]: c[a<0] = 1

第三个测试需要一点小心,因为它结合了两个测试。()这里的问题:

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都被覆盖了。在

在数组中有许多元素,并且只进行了一些测试,所以我不必担心速度。注重清晰和表达力,而不是紧凑。在

where有一个3参数版本,可以在值或数组之间进行选择。但我很少使用它,也没有看到很多关于它的问题。在

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可以链接在一行上。在

c = np.where(b>0, 3, np.where((a>0)&(b<0), 2, np.where(a>0, 0, 1)))

通过^{}可以得到这个问题的一般解决方案。您只需提供条件和选择的列表:

np.random.seed(0)

a = np.random.randint(-10, 10, (5, 5))
b = np.random.randint(-10, 10, (5, 5))

conditions = [b > 0, (a > 0) & (b < 0), a < 0, a > 0]
choices = [3, 2, 1, 0]

res = np.select(conditions, choices)

array([[3, 3, 1, 3, 1],
       [3, 3, 3, 3, 3],
       [1, 2, 1, 1, 1],
       [0, 2, 3, 3, 1],
       [1, 2, 2, 2, 1]])

正如@chrisz指出的,您当前有重叠的条件。下面是我如何使用多个if语句:

import numpy as np
a = np.random.random(50)*10 - 10
b = np.random.random(50)*10 - 10
c = [0*(a>0)*(b<0) + 1*(a<0) + 3*(a==0)*(b>0)]

如果为真,compare语句返回1,否则返回0。通过将它们相乘并添加不同的语句,可以生成多个if语句。但是,这只在if语句不重叠的情况下有效。在

相关问题 更多 >