Akshay
Akshay

Reputation: 2785

Replace all 1's at a given index - numpy

I have a binary matrix of size 10-by-10. I wanted to change all the 1's in the matrix at a given index to -1

I was able to get something like this

import numpy as np
mat = np.random.randint(2, size=(10, 10))
index = [6,7,8,9]

mat[(mat[index,:] == 1).nonzero()] = -1
print(mat)

when I print this, I get something like this

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

But this seems to be wrong as the index is at the end of the matrix, what I wanted was

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

I know that nonzero() is not need as I am already comparing the contents to 1, but That's the best I got.

What am I doing wrong? Is there a way to get the right answer?

Upvotes: 2

Views: 164

Answers (1)

Use numpy.where to select conditionally elements based on mat:

import numpy as np
mat = np.random.randint(2, size=(10, 10))
index = [6,7,8,9]

mat[index,:] = np.where(mat[index,:],-1,mat[index,:])
print(mat)

This will overwrite the given rows of mat depending on the truthiness of the original values. Where the original values in those rows were 1, they will be overwritten with -1, otherwise they will be left alone.

Although note that if you have a binary matrix with only zeroes and ones, you can just flip the sign of every element in the given rows, since 0 is invariant to this transformation:

mat[index,:] = -mat[index,:]

Upvotes: 2

Related Questions