简体   繁体   中英

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

Suppose I have a numpy array:

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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