3

I have an array of zeros

arr = np.zeros([5,5])
array([[ 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 assign values based on index so I did this .

out = np.array([[nan,2.,4.,1.,1.],[nan,3.,4.,4.,4.]])

arr[out[0].astype(int),np.arange(len(out[0]))] = 1
arr[out[1].astype(int),np.arange(len(out[1]))] = 1

Assignment works fine if there is 0 instead of nan.

How can I skip assignment in case of nan? and Is it possible to assign values at once from a multidimensional index array rather than using for loop ?

1 Answer 1

2

Mask it -

mask = ~np.isnan(out)
arr[out[0,mask[0]].astype(int),np.flatnonzero(mask[0])] = 1
arr[out[1,mask[1]].astype(int),np.flatnonzero(mask[1])] = 1

Sample run -

In [171]: out
Out[171]: 
array([[ nan,   2.,   4.,   1.,   1.],
       [ nan,   3.,   4.,   4.,   4.]])

In [172]: mask = ~np.isnan(out)
     ...: arr[out[0,mask[0]].astype(int),np.flatnonzero(mask[0])] = 1
     ...: arr[out[1,mask[1]].astype(int),np.flatnonzero(mask[1])] = 1
     ...: 

In [173]: arr
Out[173]: 
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  1.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  1.,  1.]])

Alternative, replace the flatnonzero calls with range-masking -

r = np.arange(arr.shape[1])
arr[out[0,mask[0]].astype(int),r[mask[0]]] = 1
arr[out[1,mask[1]].astype(int),r[mask[1]]] = 1

If you are working with a lot many rows than just 2 and you want to assign them in a vectorized manner, here's one method, using linear-indexing -

n = arr.shape[1]
linear_idx = (out*n + np.arange(n))
np.put(arr, linear_idx[~np.isnan(linear_idx)].astype(int), 1)
Sign up to request clarification or add additional context in comments.

3 Comments

Sir and my second question.
@Bharathshetty Where's the second question?
without using arr[out[0... and arr[out[1... is it possible to write the same in one line

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.