0

Suppose I have the following array.

l = np.asarray([1,3,5,7])

Out[552]: array([1, 3, 5, 7])

I can select the row twice using a index array np.asarray([[0,1],[1,2]]):

l[np.asarray([[0,1],[1,2]])]
Out[553]: 
array([[1, 3],
       [3, 5]])

It doesn't work if the index array have different length on each row:

l[np.asarray([[1,3],[1,2,3]])]

Traceback (most recent call last):

  File "<ipython-input-555-3ec2ab141cd4>", line 1, in <module>
    l[np.asarray([[1,3],[1,2,3]])]
IndexError: arrays used as indices must be of integer (or boolean) type

My desired output for this example would be:

array([[3, 7],
       [3, 5, 7]])

Can someone please help?

1
  • numpy doesn't support ragged (non-rectangular arrays), so you might want to think of other datastructures you could use to store your output (like lists). Commented May 3, 2017 at 0:38

2 Answers 2

1

I think this is the closest I can get.

import numpy as np
l = np.asarray([1, 3, 5, 7])
idx = [[1,3],[1,2,3]]
output = np.array([np.array(l[i]) for i in idx])
print output

Result:

[array([3, 7]) array([3, 5, 7])]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. This is closer. Maybe it can't get any better if Numpy doesn't support ragged array as @DSM mentioned.
Yeah, I think list is better for such indexing.
0

You can get the result you are after if you build the lists seperately.

Code:

l = np.asarray([1, 3, 5, 7])

# Build a sample array
print(np.array([[3, 7], [3, 5, 7]]))   

# do the lookups into the original array 
print(np.array([list(l[[1, 3]]), list(l[[1, 2, 3]])]))

Results:

[[3, 7] [3, 5, 7]]
[[3, 7] [3, 5, 7]]

2 Comments

Thanks for the answer but my index array has many rows and this method won't scale.
@Allen, Often a good idea to put these sorts of details into the question, and not left as happy surprises later.

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.