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

时间:2021-04-27 13:32:13

Suppose I have a numpy array:

假设我有一个numpy数组:

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

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

and an indices array:

和索引数组:

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

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

1 个解决方案

#1


1  

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). There are two types of advanced indexing: integer and Boolean.

当选择对象是非元组序列对象,ndarray(数据类型为integer或bool)或具有至少一个序列对象或ndarray(数据类型为integer或bool)的元组时触发。高级索引有两种类型:整数和布尔值。

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 (i.e., writing to it will not modify the original array).

您的情况是整数高级索引,您可以在其中传递要检索的索引数组。正如sascha在评论中指出的那样,这将创建数据的副本,因此新数组将独立于原始数组存在(即,写入它不会修改原始数组)。

#1


1  

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). There are two types of advanced indexing: integer and Boolean.

当选择对象是非元组序列对象,ndarray(数据类型为integer或bool)或具有至少一个序列对象或ndarray(数据类型为integer或bool)的元组时触发。高级索引有两种类型:整数和布尔值。

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 (i.e., writing to it will not modify the original array).

您的情况是整数高级索引,您可以在其中传递要检索的索引数组。正如sascha在评论中指出的那样,这将创建数据的副本,因此新数组将独立于原始数组存在(即,写入它不会修改原始数组)。