1

I am looking for an elegant way of doing the following:

I have an array like this:

[[0, 0, 0, 1],
 [0, 0, 0, 2],
 [0, 0, 0, 1]]

I want to replace the element on each row, which index is equal to the last element of that row, with 1. So for the first row I need the element with index 1 to become 1, for the second row the element with an index 2 to become 1 and so on. This is just an example, in reality I have bigger matrices and the last column has values from 0 to 9, which I need to use to indicate which element of the row to become 1.

2 Answers 2

4

IIUC, you could use advanced indexing and do something like

>>> s
array([[0, 0, 0, 1],
       [0, 0, 0, 2],
       [0, 0, 0, 1]])
>>> s[np.arange(len(s)),s[:,-1]] = 1
>>> s
array([[0, 1, 0, 1],
       [0, 0, 1, 2],
       [0, 1, 0, 1]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I never managed to organize it like this in my attempts.
1
array = [[0, 0, 0, 1], [0, 0, 0, 2], [0, 0, 0, 1]]
for row in array:
    row[row[-1]] = 1

Yields

[[0, 1, 0, 1], [0, 0, 1, 2], [0, 1, 0, 1]]

1 Comment

Thank you, this helps me too for the sake of learning, just I was preferring something without for loop.

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.