Flipping zeroes and ones in one-dimensional NumPy array

后端 未结 6 470
我在风中等你
我在风中等你 2020-12-10 10:23

I have a one-dimensional NumPy array that consists of zeroes and ones like so:

array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

I\'d li

相关标签:
6条回答
  • 2020-12-10 10:51
    answer = numpy.ones_like(a) - a
    
    0 讨论(0)
  • 2020-12-10 10:53

    I also found a way to do it:

    In [1]: from numpy import array
    
    In [2]: a = array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    
    In [3]: b = (~a.astype(bool)).astype(int)
    
    
    In [4]: print(a); print(b)
    [1 1 1 1 1 0 0 0 0 0 0 0 0 0 0]
    [0 0 0 0 0 1 1 1 1 1 1 1 1 1 1]
    

    Still, I think that @gboffi's answer is the best. I'd have upvoted it but I don't have enough reputation yet :(

    0 讨论(0)
  • 2020-12-10 10:55

    A sign that you should probably be using a boolean datatype

    a = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.bool)
    # or
    b = ~a
    b = np.logical_not(a)
    
    0 讨论(0)
  • 2020-12-10 11:00

    There must be something in your Q that i do not understand...

    Anyway

    In [2]: from numpy import array
    
    In [3]: a = array((1,0,0,1,1,0,0))
    
    In [4]: b = 1-a
    
    In [5]: print a ; print b
    [1 0 0 1 1 0 0]
    [0 1 1 0 0 1 1]
    
    In [6]: 
    
    0 讨论(0)
  • 2020-12-10 11:15

    another superfluous option:

    numpy.logical_not(a).astype(int)
    
    0 讨论(0)
  • 2020-12-10 11:17

    Mathematically, the first thing that comes to mind is (value + 1) % 2.

    >>> (a+1)%2
    array([1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)
    
    0 讨论(0)
提交回复
热议问题