numpy.take(a,indices,axis=None,out=None,mode='raise')[source]¶Take elements from an array along an axis.
When axis is not None, this function does the same thing as “fancy”indexing (indexing arrays using arrays); however, it can be easier to useif you need elements along a given axis. A call such asnp.take(arr,indices,axis=3) is equivalent toarr[:,:,:,indices,...].
Explained without fancy indexing, this is equivalent to the following useofndindex, which sets each ofii,jj, andkk to a tuple ofindices:
Ni,Nk=a.shape[:axis],a.shape[axis+1:]Nj=indices.shapeforiiinndindex(Ni):forjjinndindex(Nj):forkkinndindex(Nk):out[ii+jj+kk]=a[ii+(indices[jj],)+kk]
| Parameters: |
|
|---|---|
| Returns: |
|
See also
compressndarray.taketake_along_axisNotes
By eliminating the inner loop in the description above, and usings_ tobuild simple slice objects,take can be expressed in terms of applyingfancy indexing to each 1-d slice:
Ni,Nk=a.shape[:axis],a.shape[axis+1:]foriiinndindex(Ni):forkkinndindex(Nj):out[ii+s_[...,]+kk]=a[ii+s_[:,]+kk][indices]
For this reason, it is equivalent to (but faster than) the following useofapply_along_axis:
out=np.apply_along_axis(lambdaa_1d:a_1d[indices],axis,a)
Examples
>>>a=[4,3,5,7,6,8]>>>indices=[0,1,4]>>>np.take(a,indices)array([4, 3, 6])
In this example ifa is an ndarray, “fancy” indexing can be used.
>>>a=np.array(a)>>>a[indices]array([4, 3, 6])
Ifindices is not one dimensional, the output also has these dimensions.
>>>np.take(a,[[0,1],[2,3]])array([[4, 3], [5, 7]])