简体   繁体   English

如何获取numpy数组中非连续索引的元素?

[英]How to get elements for non-contiguous indices in a numpy array?

Suppose I have a numpy array: 假设我有一个numpy数组:

arr = np.array([1,2,3,4,4,5,3,2,10])

and an indices array: 和一个索引数组:

indices = np.array([0,1,4,6])

I could write a simple function that does the job, but I was wondering if numpy has a built-function like np.get(arr, indices) which returns, in this case, np.array([1,2,4,3] . 我可以编写一个简单的函数来完成这项工作,但是我想知道numpy是否具有像np.get(arr, indices)这样的内置函数,在这种情况下,它返回np.array([1,2,4,3]

This is called Advanced Indexing : 这称为高级索引

triggered when the selection object is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). 当选择对象是非元组序列对象,ndarray(数据类型为整数或布尔值)或具有至少一个序列对象或ndarray(数据类型为整数或布尔值)的元组时触发。 There are two types of advanced indexing: integer and Boolean. 有两种类型的高级索引:整数和布尔值。

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view). 高级索引总是返回数据的副本(与返回视图的基本切片相反)。

Your situation is integer advanced indexing, where you pass an array of indexes to be retrieved. 您的情况是整数高级索引,在此传递要检索的索引数组。 As sascha noted in comments, this will create a copy of the data, so the new array will exist independently from the original one (ie, writing to it will not modify the original array). 正如sascha在评论中指出的那样,这将创建数据的副本,因此新数组将独立于原始数组而存在(即,写入该数组不会修改原始数组)。

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

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