python - 有选择地否定数组中的元素

标签 python arrays numpy

我正在寻找有关 numpy 中“如何有选择地否定数组的值”的帮助。

已经尝试过,numpy.where()numpy.negative 但无法在选定的几个上实现条件。

import numpy as np

arr=np.arange(11)
arr

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

假设我只想取反数组中 2 到 8 之间的所有元素

array([ 0,  1,  2,  -3,  -4,  -5,  -6,  -7,  8,  9, 10])

最佳答案

使用按位与创建掩码,并乘以-1:

m = (arr > 2) & (arr < 8)
arr[m] *= -1

array([ 0,  1,  2, -3, -4, -5, -6, -7,  8,  9, 10])

关于python - 有选择地否定数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53551577/

相关文章:

python - 同时运行 model.fit() 和 TensorBoard?

python - 如何保留Python字典中的项目顺序?

c++ - 打印2D动态数组C++函数

python - 使用 fromfunction 和数组填充 numpy 矩阵

python - 基于 Pandas 范围的 bin 值

python - numpy 1.9.2+MKL 与 py2exe 打包时出现 OMP 警告

python - 在Python中模拟SHL和SHR ASM指令

python - 转换 pandas 数据框中包含 nan、连字符和逗号的列的数据类型

python - Mechanize 上传图片返回 403 错误

arrays - D 数组是零散的吗?