It seems that numpy.take(array, indices)
and numpy.choose(indices, array)
return the same thing: a subset of array
indexed by indices
.
Are there only subtle differences between the two, or am I missing something more important? And is there a reason to prefer one over the other?
The numpy take() function takes elements from an array along an axis. The take() function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need items along the given axis.
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension. The Python core library provided Lists.
Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.
numpy.take(array, indices)
and numpy.choose(indices, array)
behave similarly on 1-D arrays, but this is just coincidence. As pointed out by jonrsharpe, they behave differently on higher-dimensional arrays.
numpy.take(array, indices)
picks out elements from a flattened version of array
. (The resulting elements are of course not necessarily from the same row.)
For example,
numpy.take([[1, 2], [3, 4]], [0, 3])
returns
array([1, 4])
numpy.choose(indices, set_of_arrays)
plucks out element 0 from array indices[0]
, element 1 from array indices[1]
, element 2 from array indices[2]
, and so on. (Here, array
is actually a set of arrays.)
For example
numpy.choose([0, 1, 0, 0], [[1, 2, 3, 4], [4, 5, 6, 7]])
returns
array([1, 5, 3, 4])
because element 0 comes from array 0, element 1 comes from array 1, element 2 comes from array 0, and element 3 comes from array 0.
These descriptions are simplified – full descriptions can be found here: numpy.take, numpy.choose. For example, numpy.take
and numpy.choose
behave similarly when indices
and array
are 1-D because numpy.choose
first broadcasts array
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With