2

Assume you have a numpy array as array([[5],[1,2],[5,6,7],[5],[5]]). Is there a function, such as np.where, that can be used to return all row indices where [5] is the row value? For example, in the array above, the returned values should be [0, 3, 4] indicating the [5] row numbers.

Please note that each row in the array can differ in length.

Thanks folks, you all deserve best answer, but i gave the green mark to the first one :)

2
  • Are you sure you even want an array here? What are you doing that would best be solved by a 1-dimensional array of variable-length lists? Commented Aug 3, 2013 at 5:49
  • In the real problem, those [5]'s are [?] indicating missing data, which I want them removed from the dataset. One way is to initialize another array that takes the row indices where [?] is not present. The reason why the structure is erratic is because some samples correspond to more than one class. Sorry about the Machine learning jargon, but thats the only way i can think of for explaining the importance of such arrays. Commented Aug 3, 2013 at 6:06

3 Answers 3

3

This should do it:

[i[0] for i,v in np.ndenumerate(ar) if v == [5]]
=> [0, 3, 4]
Sign up to request clarification or add additional context in comments.

Comments

3

If you check ndim of your array you will see that it is actually not a multi-dimensional array, but a 1d array of list objects.

You can use the following list comprehension to get the indices where 5 appears:

[i[0] for i,v in np.ndenumerate(a) if 5 in v]
#[0, 2, 3, 4]

Or the following list comprehension to get the indices where the list is exactly [5]:

[i[0] for i,v in np.ndenumerate(a) if v == [5]]
#[0, 3, 4]

Comments

2

You could use the the list comprehension as here:

[i[0] for i,v in np.ndenumerate(a) if 5 in v]
#[0, 2, 3, 4]

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.