Jack Rolph
Jack Rolph

Reputation: 595

Making new Numpy array with indexes of another Numpy array

I have an 10 x N array as follows:

[[ 0.  1.  0. ...,  0.  0.  0.]
 [ 0.  0.  0. ...,  1.  0.  0.]
 [ 1.  0.  0. ...,  0.  0.  0.]
 ..., 
 [ 0.  0.  0. ...,  1.  0.  0.]
 [ 0.  0.  0. ...,  0.  0.  1.]
 [ 0.  0.  0. ...,  0.  0.  1.]]

I want a Numpy array of the following 1 x N format, where each element in the new array is the value of the index filled with '1' in the 10 x N array.

For example, the process would convert the above into the array:

[[ 1.  7.  0. ...,  7,  9.  9.]]

I have had some success with using the function:

np.where(array > 0)[0][0]

This gives me a value for my final array but my attempts to fill the array in the required format have not worked. Furthermore, my implementations have not been very pythonic. Is there a pythonic solution to the above question?

Upvotes: 1

Views: 42

Answers (1)

user3483203
user3483203

Reputation: 51165

Setup

a = np.array([[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 1, 0, 0, 0]])

You only care about the column, since your second array is 1D, right now you are grabbing the row from numpy.where

If you can guarantee that there is only one 1 per row, just grab the columns from the output of numpy.where:

np.where(a==1)[1]

array([5, 0, 2, 4, 2, 6], dtype=int64)

Upvotes: 1

Related Questions