python,numpy布尔数组:where语句中的否定 [英] python, numpy boolean array: negation in where statement

查看:106
本文介绍了python,numpy布尔数组:where语句中的否定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有:

import numpy as np
array = get_array()

我需要做以下事情:

for i in range(len(array)):
    if random.uniform(0, 1) < prob:
        array[i] = not array[i]

其中array为numpy.array.

with array being a 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'):

具有多个元素的数组的真值是不明确的.使用a.any()或a.all()

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

为什么我可以采用array的值而不是取反?

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.

谢谢您的帮助

p.s .:我不在乎该语句是否修改数组.我只需要操作的结果.

p.s.: I don't care if the statement modifies array or not. I just need the result of the operation.

另一个问题:我要进行此更改有两个原因:可读性和效率.它有真正的性能改进吗?再次谢谢你

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

推荐答案

我建议使用

array ^= numpy.random.rand(len(array)) < prob

这可能是获得所需结果的最有效方法.它将使用"xor"来对数组进行适当的修改,以将随机条件对其求值为True的条目求反.

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 True for.

为什么我可以采用array的值而不是取反?

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()

not运算符隐式尝试将其操作数转换为bool,然后返回相反的真值.无法使not重载以执行任何其他行为.要对bool s的NumPy数组求反,可以使用

The not operator implicitly tries to convert its operand to bool, and then returns the opposite truth value. It is not possible to overload not to perform any other behaviour. To negate a NumPy array of bools, you can use

~array

numpy.logical_not(array)

numpy.invert(array)

尽管.

这篇关于python,numpy布尔数组:where语句中的否定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆