简体   繁体   English

numpy:使用不同的索引数组多次选择行

[英]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]]) : 我可以使用索引数组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? 有人可以帮忙吗?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM