Indexing a 2d array with another 2d array

Viewed 105

I have an array lines = np.array[[0,0],[0,1],[1,0],[1,2],[2,0],[2,1],[2,3],[3,1],[3,3],[0,1],[1,2],[4,4]] and another numpy zeros array vectors = [[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.],[0. 0. 0. 0. 0.]] I want to use the elements in the first array(lines) to insert "1's" into the second array(vectors).

So my desired output would be:

vectors = 
[[1. 1. 1. 0. 0.],
[1. 0. 1. 1. 0.],
[0. 1. 0. 0. 0.],
[0. 0. 1. 1. 0.],
[0. 0. 0. 0. 1.]]

Note: Take into account in the lines array all the second numbers are used to index a particular array in the vectors array and the first number is where to place the "1". e.g., lines[2] = [1,0], lines[2][1] = 0 and lines[2][0] = 1 so you will use the 0 to index into the 0th array in the vectors array and place a "1" in the 1st position(index 1).

Apologies if I explained it badly I am new to python and StackOverflow.

1 Answers

Use: vectors[lines[:, 1], lines[:, 0]] = 1

Explanation: lines[:, n] indexes the nth column of the 2-D lines array. So according to your specifications, lines[:, 1] (the first column) contains the row numbers of the vectors array. Then we use lines[:, 0] (i.e. values in the zeroth column) to substitute in appropriate columns in the vectors array.

Related