1

I have an array that looks something like this:

np.array([[0 , 5, 1], [0, 0, 3], [1, 7, 0]])

I want to check that each element is nonzero, and if it is nonzero replace it with a number that tracks how many elements it has checked. That is, I want the final product to look like

np.array([[0, 2, 3], [0, 0, 6], [7, 8, 0]])

where the first row reads [0, 2, 3] because the second element was checked second, passed the test, and then replaced (and so on). Can anyone think of any solutions? I imagine that numpy's indexing will be quite useful here. Thanks!

1
  • "I imagine that numpy's indexing will be quite useful here." Sure, so what did you try from that hunch? Commented Sep 26, 2019 at 10:52

2 Answers 2

3

You can do:

np.where(a == 0, a, np.arange(a.size).reshape(a.shape) + 1)
Sign up to request clarification or add additional context in comments.

1 Comment

Incredibly elegant solution, I will have to spend some more time with the np.where() function in the future! Thanks :)
1

In case if you need to modify the initial array - additional approach using mask array:

(from IPython interactive console session)

In [211]: arr = np.array([[0, 5, 1], [0, 0, 3], [1, 7, 0]])

In [212]: m = arr.nonzero()

In [213]: arr[m] = np.arange(1, arr.size+1).reshape(arr.shape)[m]

In [214]: arr
Out[214]: 
array([[0, 2, 3],
       [0, 0, 6],
       [7, 8, 0]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.