Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace 1 by 0 and -1 by 1 everywhere 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.

like image 965
Katja Avatar asked Sep 10 '25 14:09

Katja


2 Answers

You can try this:

import numpy as np

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

a[a == 1] = 0
a[a == -1] = 1

print(a)

Output:

[[1 0 1]
 [1 0 0]]
like image 65
Sabil Avatar answered Sep 13 '25 04:09

Sabil


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

like image 45
Mark Lavin Avatar answered Sep 13 '25 04:09

Mark Lavin