2

Given an array defined below as:

a = np.arange(30).reshape((3, 10)
col_index = [[1,2,3,5], [3,4,5,7]]
row_index = [2,1]

Is it possible to index a[row_index, col_index], so I can do something like a[row_index, col_index] =1, so then a becomes

[[0,1,2,3,4,5,6,7,8,9], [10,11,12,1,1,1,16,1,18,19], [20,1,1,1,24,1,26,27,28,29]]

So to clarify, in row 2, column 1,2,3, and 5 are set to one, and in row 1, column 3,4,5,7 is also set to 1.

1
  • OP, You can only accept one answer, not multiple. When you accept another answer, the first one is automatically unaccepted. Commented Jan 14, 2018 at 0:19

1 Answer 1

2

Or (if you don't like typing)

a[np.c_[row_index], col_index] = 1

or even shorter but Python 2 only

a[zip(row_index), col_index] = 1

What all these solutions do is to make row and col indices broadcastable to each other. np.c_ is the column concatenation convenience object. It makes columns out of 1D objects. zip used to do essentially the same. Only, since Python 3 it returns an iterator instead of a list and numpy can't handle those. (One could do list(zip(row_index)) but that's not short.)

Sign up to request clarification or add additional context in comments.

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.