Allen Qin
Allen Qin

Reputation: 19947

Numpy: Select row multiple times using different indices array

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?

Upvotes: 0

Views: 531

Answers (2)

Chih-Hsu Jack Lin
Chih-Hsu Jack Lin

Reputation: 453

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])]

Upvotes: 1

Stephen Rauch
Stephen Rauch

Reputation: 49794

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]]

Upvotes: 0

Related Questions