0

I have a numpy.ndarray containing numpy.ndarray's of different size and i want to extract some rows where the first number of each of these rows are in a certain list.

Example:

>>>a
array([array([1]), array([2, 3]), array([3, 1, 1]), array([2, 3, 3, 4])], dtype=object)

>>> idx
[2]

I need:

>>>a
array([array([2, 3]), array([2, 3, 3, 4])], dtype=object)

So i want only the rows (or arrays) of a which have a 2 as the first number. Is there a simple and nice way to do so like in this post here?

1 Answer 1

2

An object dtype array like this is more like a list of lists than a 2d array. a actually has pointers to the element arrays, just a list would.

In [517]: a=array([array([1]), array([2, 3]), array([3, 1, 1]), array([2, 3, 3, 4])], dtype=object)
In [518]: a
Out[518]: 
array([array([1]), array([2, 3]), array([3, 1, 1]), array([2, 3, 3, 4])],
      dtype=object)

A straightforward way of selecting the elements of a that match this criteria is to use a list comprehension:

In [519]: [row for row in a if row[0]==2]
Out[519]: [array([2, 3]), array([2, 3, 3, 4])]

Almost all operations on an object dtype array like this involve a list iteration like this.

Sign up to request clarification or add additional context in comments.

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.