Home > other >  Finding index of a value in Numpy matrix and add it with another value
Finding index of a value in Numpy matrix and add it with another value

Time:12-28

I want to find the index of a value in a matrix and add it to another value. How should I do that? I did as follows but does not work. Merci for your help. result should be 0.

import numpy as np

a=np.array([1, 2, 3, 4, 78, 55, 33 ,22])

index=np.where(a==3)

newnumber=index-2

CodePudding user response:

You are very close. Your solution right now is not quite working because np.where is returning a tuple containing an array with the index satisfying the condition. To make it work, all you need to do is to unpack the tuple with your prefferred method (could be index, = np.where(a==3) or index = np.where(a==3)[0] or whatever).

In the future, I recommend you inspect your variables when you get an unexpected result. In tis case, doing print(index) would have bee enough!

CodePudding user response:

You have two problems - ambiguity at to what you want to subtract, and the tuple nature of the where result.

Your array and the test:

In [47]: a=np.array([1, 2, 3, 4, 78, 55, 33 ,22])
In [48]: a==3
Out[48]: array([False, False,  True, False, False, False, False, False])

That boolean mask can be used directly to index a:

In [49]: a[a==3]
Out[49]: array([3])

and to change the value of that element(s):

In [50]: a[a==3] -= 2
In [51]: a
Out[51]: array([ 1,  2,  1,  4, 78, 55, 33, 22])

where on the boolean mask produces a tuple (reread the np.where/nonzero docs):

In [52]: np.where(Out[48])
Out[52]: (array([2]),)

We can't subtract a value from this tuple:

In [53]: np.where(Out[48])-2
Traceback (most recent call last):
  File "<ipython-input-53-fd4087ff32d9>", line 1, in <module>
    np.where(Out[48])-2
TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

We can extract the array from the tuple, and subtract a value from that:

In [54]: np.where(Out[48])[0]-2
Out[54]: array([0])

That's just the index of the element 2 steps before the 3. Is that what you really want?

  • Related