繁体   English   中英

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

[英]Numpy: Select row multiple times using different indices array

假设我有以下数组。

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

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

我可以使用索引数组np.asarray([[0,1],[1,2]])选择该行两次:

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

如果索引数组在每行上具有不同的长度,则不起作用:

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

我希望此示例的输出为:

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

有人可以帮忙吗?

我认为这是我能得到的最接近的。

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

结果:

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

如果单独构建列表,则可以获得您想要的结果。

码:

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

结果:

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

暂无
暂无

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

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