Mer*_*raj 1 python arrays numpy
我正在寻找有关 numpy 中“如何有选择地否定数组的值”的一些帮助。
已经尝试过,numpy.where()而numpy.negative却无法实现对选定的几个条件。
import numpy as np
arr=np.arange(11)
arr
Run Code Online (Sandbox Code Playgroud)
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Run Code Online (Sandbox Code Playgroud)
假设我只想否定数组中 2 到 8 之间的所有元素
array([ 0, 1, 2, -3, -4, -5, -6, -7, 8, 9, 10])
Run Code Online (Sandbox Code Playgroud)
使用按位 AND 创建一个掩码,然后乘以-1:
m = (arr > 2) & (arr < 8)
arr[m] *= -1
Run Code Online (Sandbox Code Playgroud)
array([ 0, 1, 2, -3, -4, -5, -6, -7, 8, 9, 10])
Run Code Online (Sandbox Code Playgroud)