I have a matrix in scipy. And I'm trying to replace it with a 1 if it meets a certain condition, and a 0 if it doesnt.
for a in range(0,l):
for b in range(0,l):
if Matrix[a][b] == value:
Matrix[a][b] = 1
else:
Matrix[a][b] = 0
My matrix is full of elements that have the "value" in it. Yet it's giving me the output as a matrix that is entirely 0's.
This worked before on a similar script. Is it perhaps something to with the structure of the matrix?
Here's how the matrix looks at first--
[ [0 1. 1. 2.]
[1. 0. 2. 1.]
[1. 2. 0. 1.]
[2. 1. 1. 0.]]
When i set value == 1. I get all the 1's to 1's, and all the 2's to zero. Which is what I want.
But, when i set value == 2. I get everything to zero.
when I do all of what has been suggested.
[[ 0. 1. 1. 2. 1. 2. 2. 3.]
[ 1. 0. 2. 1. 2. 1. 3. 2.]
[ 1. 2. 0. 1. 2. 3. 1. 2.]
[ 2. 1. 1. 0. 3. 2. 2. 1.]
[ 1. 2. 2. 3. 0. 1. 1. 2.]
[ 2. 1. 3. 2. 1. 0. 2. 1.]
[ 2. 3. 1. 2. 1. 2. 0. 1.]
[ 3. 2. 2. 1. 2. 1. 1. 0.]]
>> np.where(matrix==2,1,0)
>> array([[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]])
If you actually have a matrix there, rather than an ndarray, then
Matrix[a]
is a 1-row matrix, and 2D. Similarly,
Matrix[a][b]
is also a matrix (or an IndexError, since Matrix[a]
only has 1 row). You need to use
Matrix[a, b]
to get the elements. This is one of the reasons why using matrices can be awkward. Note that you could just use
Matrix == value
to get a matrix of booleans, and then use astype
to convert it to the type you want. This would be less code, and it'd run faster. Thus, if your dtype is int32, the whole loopy thing you've posted could be replaced by
return (Matrix == value).astype(numpy.int32)
or if you really want to modify the array in place, you can use the numpy.equal
ufunc with an out
parameter:
numpy.equal(Matrix, value, out=Matrix)
You can use np.where
to do this.
Given:
>>> matrix
array([[0, 1, 1, 2],
[1, 0, 2, 1],
[1, 2, 0, 1],
[2, 1, 1, 0]])
This replaces 2
values in matrix
with 0
and leaves the other values alone:
>>> np.where(matrix==2,0,matrix)
array([[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]])
Or this replaces 2
values with 0
and any other value with 1
:
>>> np.where(matrix==2,0,1)
array([[1, 1, 1, 0],
[1, 1, 0, 1],
[1, 0, 1, 1],
[0, 1, 1, 1]])
Even:
>>> np.where(matrix==2,' a two','not two')
array([['not two', 'not two', 'not two', ' a two'],
['not two', 'not two', ' a two', 'not two'],
['not two', ' a two', 'not two', 'not two'],
[' a two', 'not two', 'not two', 'not two']],
dtype='<U7')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With