Tsubaki Hana
Tsubaki Hana

Reputation: 33

Replacing value in a numpy array using as an index another value from the same array

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.

Upvotes: 1

Views: 3830

Answers (2)

Celeo
Celeo

Reputation: 5682

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]]

Upvotes: 1

DSM
DSM

Reputation: 352979

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]])

Upvotes: 4

Related Questions