简体   繁体   中英

Replace all Zeros by Ones in a numpy array

I have a numpy array:

a = np.array([[-1,1,-1],[-1,1,1]])

My array only contains two different values: -1 and 1. However, I want to replace all 1's by 0 and all -1's by 1. Of course I can loop over my array, check the value of every field and replace it. This will work for sure, but I was looking for a more convenient way to do it.

I am looking for some sort of

replace(old, new) 

function.

You can try this:

import numpy as np


a = np.array([[-1,1,-1],[-1,1,1]])

# approach 1
a[a == 1] = 0
a[a == -1] = 1

# approach 2
mask = a == 1
a[mask] = 0
a[~mask] = 1

print(a)

Output:

[[1 0 1]
 [1 0 0]]

The correct answer is by @Tusamma Sal Sabil, in terms of speed here is a little improvement on his response:

import numpy as np

a = np.array([[-1,1,-1],[-1,1,1]])
mask = a == 1
a[mask] = 0
a[~mask] = 1

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

Try (a == -1 ).astype(np.int32)

Here you go!

import numpy as np


if __name__ == "__main__":
    a = np.array([[-1,1,-1],[-1,1,1]])
    a[a == 1] = 0
    a[a == -1] = 1
    print(a)

import numpy as np

sample_arr = np.ones((5,2))
print('Converting an array with ones to zero')
np.where(sample_arr==1, 0, sample_arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM