Search code examples
pythonnumpywhere-clause

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


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

Solution

  • 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 preferred 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 this case, doing print(index) would have bee enough!