python,numpy布尔数组:where语句中的否定

python,numpy布尔数组:where语句中的否定,python,numpy,Python,Numpy,与: 我需要做以下事情: import numpy as np array = get_array() 范围内i的(len(数组)): 如果随机。均匀(0,1)

与:

我需要做以下事情:

import numpy as np
array = get_array()
范围内i的
(len(数组)):
如果随机。均匀(0,1)
数组为numpy.array

我希望我能做类似的事情:

for i in range(len(array)):
    if random.uniform(0, 1) < prob:
        array[i] = not array[i]
array=np.where(np.random.rand(len(array))
但我得到了以下结果(指“notarray”):

包含多个元素的数组的真值不明确。使用a.any()或a.all()

为什么我可以接受数组的值而不是它的反数

目前,我解决了以下问题:

array = np.where(np.random.rand(len(array)) < prob, not array, array)
array=np.where(np.random.rand(len(array))
但在我看来,这真的很笨拙

谢谢你的帮助

p、 s:我不在乎语句是否修改数组。我只需要手术的结果

还有一个问题:我想做这个改变有两个原因:可读性和效率。它是否有真正的性能改进?再次感谢您

也许会帮助您继续前进。

我建议使用

array = np.where(np.random.rand(len(array)) < prob, - array + 1, array)
not
运算符隐式尝试将其操作数转换为
bool
,然后返回相反的真值。不可能过载
not
来执行任何其他行为。要对
bool
s的NumPy数组求反,可以使用

>>> bool(array)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


但是。

putmask
如果要替换选定的元素,则非常有效:

numpy.invert(array)
将numpy导入为np
np.putmask(array,numpy.random.rand(array.shape)
logical\u没有成功。但我不能完全理解“简单”与“不简单”的区别。关键是
非数组
是不明确的:在Python中,几乎任何东西都可以作为布尔值进行合理的求值,因此解释器不清楚是要元素求反还是数组对象求反,被认为是布尔值。@heapOverflow:这可能与您有关。谢谢,为了防止答案因链接腐烂而变得无用,请不要发布仅链接的答案。请将链接的要点编辑到答案中。还有np.negative(数组)
~array
numpy.logical_not(array)
numpy.invert(array)
import numpy as np

np.putmask(array, numpy.random.rand(array.shape) < prob, np.logical_not(array))