1

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?

asked Dec 7, 2018 at 16:10

1 Answer 1

1

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)
answered Dec 7, 2018 at 16:18
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you! :D

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.