快速过滤numpy数组值的方法

mi7gmzs6  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(112)

我想根据另一个数组中的值过滤一个numpy数组:

  • 如果来自另一个数组的值为正,则在该数组中保持其不变,
  • 如果另一个数组中的值为0,则将此数组中的值更改为0,
  • 如果另一个数组中的值为负,则反转该数组中的值的符号,

目前我有:

import numpy as np
this = np.array([1, 2, -3, 4])
other = np.array([0, -5, -6, 7])

this[other == 0] = 0
this[other < 0] *= -1
print(this)
# [ 0 -2  3  4]

如图所示,它需要循环other两次以获得值等于或小于0的索引,并且需要循环this两次以更改值。有更快的方法吗?(假设thisother是非常大的数组)

brc7rcf0

brc7rcf01#

使用np.sign函数来获得数字符号的指示:

this * np.sign(other)
array([ 0, -2,  3,  4])

相关问题