简体   繁体   English

NumPy 通过索引获取多行的快速方法

[英]NumPy Fast Way To Get Multiple Rows By Indexes

Given a multidimensional array of shape (6, 100, 2) , and a list of indexes (for example: [1,2,3,1,5,0,0,0,1] ) and I would like to get a numpy ndarray with the data as in these indexes (meaning, the output shape is (9, 100, 2) and rows 6,7,8 are duplicates of each other).给定一个形状为(6, 100, 2)的多维数组和一个索引列表(例如: [1,2,3,1,5,0,0,0,1] ),我想得到一个numpy ndarray 与这些索引中的数据(意思是,输出形状是(9, 100, 2)并且第 6,7,8 行彼此重复)。

The naive solution:天真的解决方案:

arr = []
indexes = [1,2,3,1,5,0,0,0,1]
for i in indexes:
  arr.append(data[i])
arr = np.stack(arr)

This naive solution wastes a lot of time in __getitem__ and the stack operation, and I was wondering if there is a faster way to do this with numpy?这种幼稚的解决方案在__getitem__stack操作中浪费了很多时间,我想知道是否有更快的方法来使用 numpy 来做到这一点?

You can just use subscripting.您可以只使用下标。 So if data is your 6×100×2 matrix, and indexes is your list of indexes, you can retrieve the result with:因此,如果data是您的 6×100×2 矩阵,而indexes是您的索引列表,您可以使用以下命令检索结果:

result = data[indexes]

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

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