Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all values in a numpy array with zero except one specific value?

I have a 2D numpy array with 'n' unique values. I want to produce a binary matrix, where all values are replaced with 'zero' and a value which I specify is assigned as 'one'.

For example, I have an array as follows and I want all instances of 35 to be assigned 'one':

array([[12, 35, 12, 26],
       [35, 35, 12, 26]])

I am trying to get the following output:

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

what is the most efficient way to do it in Python?

like image 511
user121 Avatar asked Nov 28 '22 10:11

user121


1 Answers

import numpy as np
x = np.array([[12, 35, 12, 26], [35, 35, 12, 26]])
(x == 35).astype(int)

will give you:

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

The == operator in numpy performs an element-wise comparison, and when converting booleans to ints True is encoded as 1 and False as 0.

like image 101
yuji Avatar answered Dec 05 '22 15:12

yuji