python, numpy boolean array: negation in where statement

前端 未结 3 842
夕颜
夕颜 2020-12-15 21:53

with:

import numpy as np
array = get_array()

I need to do the following thing:

for i in range(len(array)):
    if random.un         


        
相关标签:
3条回答
  • 2020-12-15 22:24

    putmask is very efficient if you want to replace selected elements:

    import numpy as np
    
    np.putmask(array, numpy.random.rand(array.shape) < prob, np.logical_not(array))
    
    0 讨论(0)
  • 2020-12-15 22:30

    Perhaps this will help you to move on.

    0 讨论(0)
  • 2020-12-15 22:33

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

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

    or

    numpy.logical_not(array)
    

    or

    numpy.invert(array)
    

    though.

    0 讨论(0)
提交回复
热议问题