此问题与以下帖子相关:Replacing Numpy elements if condition is met .
假设我有两个一维 numpy 数组 a
和 b
,每个数组有 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 循环?
最佳答案
一个直接的解决方案是按顺序应用分配。
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])
从具有“默认”值的数组开始:
In [22]: c = np.zeros_like(a)
应用第二个条件:
In [23]: c[a<0] = 1
第三个需要一点小心,因为它结合了 2 个测试。 () 事项在这里:
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)))
关于python - 有多个条件时替换numpy数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49135539/