1

Having an arbitrary 2d array, say of zeros, and an array of indices:

z = np.zeros((5,5))
ix = np.array([1,4,2,3,0])

How could I add a 1 from the columns specified by a 1d array onwards, in order to obtain:

array([[0, 1, 1, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 1, 1, 1, 1]])

I have not been able to find a simple way of doing so using numpy.

1 Answer 1

1

One way would be -

In [50]: ncols = 5

In [51]: (ix[:,None] <= np.arange(ncols)).view('i1')
Out[51]: 
array([[0, 1, 1, 1, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 1, 1, 1],
       [0, 0, 0, 1, 1],
       [1, 1, 1, 1, 1]], dtype=int8)

If you have to add to an existing array z -

z += (ix[:,None] <= np.arange(ncols))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! Pretty nice solution. One doubt, what is the reason of using view here rather than say astype?
@yatu Just for memory efficiency and hence performance, being a view.
Ah of course, astype is creating a copy of the array. Got it, thanks!

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.