Movatterモバイル変換


[0]ホーム

URL:


SciPy

numpy.take

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:
a:array_like (Ni…, M, Nk…)

The source array.

indices:array_like (Nj…)

The indices of the values to extract.

New in version 1.8.0.

Also allow scalars for indices.

axis:int, optional

The axis over which to select values. By default, the flattenedinput array is used.

out:ndarray, optional (Ni…, Nj…, Nk…)

If provided, the result will be placed in this array. It shouldbe of the appropriate shape and dtype.

mode:{‘raise’, ‘wrap’, ‘clip’}, optional

Specifies how out-of-bounds indices will behave.

  • ‘raise’ – raise an error (default)
  • ‘wrap’ – wrap around
  • ‘clip’ – clip to the range

‘clip’ mode means that all indices that are too large are replacedby the index that addresses the last element along that axis. Notethat this disables indexing with negative numbers.

Returns:
out:ndarray (Ni…, Nj…, Nk…)

The returned array has the same type asa.

See also

compress
Take elements using a boolean mask
ndarray.take
equivalent method
take_along_axis
Take elements by matching the array and the index arrays

Notes

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

Previous topic

numpy.triu_indices_from

Next topic

numpy.take_along_axis

Quick search

  • © Copyright 2008-2018, The SciPy community.
  • Last updated on Jul 24, 2018.
  • Created usingSphinx 1.6.6.

[8]ページ先頭

©2009-2025 Movatter.jp