在二进制数组中反转0和1

flo*_*o29 3 python numpy

Numpy中是否有一个函数在二进制数组中反转0和1?如果

a = np.array([0, 1, 0, 1, 1])
Run Code Online (Sandbox Code Playgroud)

我想得到:

b = [1, 0, 1, 0, 0]
Run Code Online (Sandbox Code Playgroud)

我用:

b[a==0] = 1
b[a==1] = 0
Run Code Online (Sandbox Code Playgroud)

但也许它已经在Numpy中存在了这样做.

shi*_*vsn 13

你可以简单地做:

In[1]:b=1-a
In[2]:b
Out[2]: array([1, 0, 1, 0, 0])
Run Code Online (Sandbox Code Playgroud)

要么

In[22]:b=(~a.astype(bool)).astype(int)
Out[22]: array([1, 0, 1, 0, 0])
Run Code Online (Sandbox Code Playgroud)


Kas*_*mvd 8

功能方法:

>>> np.logical_not(a).astype(int)
array([1, 0, 1, 0, 0])
Run Code Online (Sandbox Code Playgroud)