python,numpy布尔数组:where语句中的否定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4992040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python, numpy boolean array: negation in where statement
提问by heapOverflow
with:
和:
import numpy as np
array = get_array()
I need to do the following thing:
我需要做以下事情:
for i in range(len(array)):
if random.uniform(0, 1) < prob:
array[i] = not array[i]
with array being a numpy.array.
数组是一个 numpy.array。
I wish I could do something similar to:
我希望我可以做类似的事情:
array = np.where(np.random.rand(len(array)) < prob, not array, array)
but I obtain the following result (referring to 'not array'):
但我得到以下结果(指的是“非数组”):
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
包含多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()
Why can I take the value of array but not its negation?
为什么我可以取数组的值而不是它的否定?
Currently I solved with:
目前我解决了:
array = np.where(np.random.rand(len(array)) < prob, - array + 1, array)
but it looks really clumsy to me.
但在我看来真的很笨拙。
Thank you for your help
感谢您的帮助
p.s.: I don't care if the statement modifies array or not. I just need the result of the operation.
ps:我不在乎语句是否修改数组。我只需要操作的结果。
just another question: I want to do this change for 2 reasons: readability and efficiency. Is there a real performance improvement with it? Thank you again
只是另一个问题:我想做这个改变有两个原因:可读性和效率。它有真正的性能改进吗?再次感谢你
采纳答案by Sven Marnach
I suggest using
我建议使用
array ^= numpy.random.rand(len(array)) < prob
This is probably the most efficient way of getting the desired result. It will modify the array in place, using "xor" to invert the entries which the random condition evaluates to Truefor.
这可能是获得所需结果的最有效方法。它将就地修改数组,使用“xor”来反转随机条件评估的条目True。
Why can I take the value of array but not its negation?
为什么我可以取数组的值而不是它的否定?
You can't take the truth value of the array either:
你也不能取数组的真值:
>>> bool(array)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The notoperator implicitly tries to convert its operand to bool, and then returns the opposite truth value. It is not possible to overload notto perform any other behaviour. To negate a NumPy array of bools, you can use
该not运营商将暗中给它的操作数转换bool,然后返回相反的真假值。不可能超载not以执行任何其他行为。要否定bools的 NumPy 数组,您可以使用
~array
or
或者
numpy.logical_not(array)
or
或者
numpy.invert(array)
though.
尽管。
回答by eumiro
putmaskis very efficient if you want to replace selected elements:
putmask如果要替换所选元素,则非常有效:
import numpy as np
np.putmask(array, numpy.random.rand(array.shape) < prob, np.logical_not(array))

