mixle.engines.numpy_engine module¶
NumPy implementation of the ComputeEngine protocol.
- class NumpyEngine(dtype=None, prefer_fused=False)[source]
Bases:
ComputeEngineHost NumPy/SciPy engine used by the default local execution path.
- Parameters:
dtype (Any)
prefer_fused (bool)
- name = 'numpy'
- supports_autograd = False
- supports_numba = True
- resident_estep = False
- device = 'cpu'
- prefer_fused = False
- property accumulator_dtype: Any
High-precision dtype for sufficient-statistic reductions (always float64).
Reductions that aggregate over observations (the sum/index-add forming sufficient statistics) accumulate in this dtype even when scoring runs in reduced precision, so a float32 fit does not drift on large N (e.g. catastrophic cancellation in a variance).
- with_precision(precision)[source]
Return a NumPy engine using
precisionfor floating arrays.- Parameters:
precision (Any)
- Return type:
NumpyEngine
- asarray(x, dtype=None)[source]
Convert
xto a NumPy ndarray under the engine dtype policy.
- zeros(shape, dtype=None)[source]
Allocate a NumPy zero array using the configured float dtype.
- empty(shape, dtype=None)[source]
Allocate an uninitialized NumPy array using the configured float dtype.
- arange(*args, **kwargs)[source]
Return
np.arangewith float ranges honoring the precision policy.
- stack(arrays, axis=0)[source]
Stack arrays with
np.stackalong the requested axis.
- log = <ufunc 'log'>
- exp = <ufunc 'exp'>
- sqrt = <ufunc 'sqrt'>
- abs = <ufunc 'absolute'>
- static where(condition, [x, y, ]/)
Return elements chosen from x or y depending on condition.
Note
When only condition is provided, this function is a shorthand for
np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided.- Parameters:
condition (array_like, bool) – Where True, yield x, otherwise yield y.
x (array_like) – Values from which to choose. x, y and condition need to be broadcastable to some shape.
y (array_like) – Values from which to choose. x, y and condition need to be broadcastable to some shape.
- Returns:
out – An array with elements from x where condition is True, and elements from y elsewhere.
- Return type:
ndarray
See also
choosenonzeroThe function that is called when x and y are omitted
Notes
If all the arrays are 1-D, where is equivalent to:
[xv if c else yv for c, xv, yv in zip(condition, x, y)]
Examples
>>> import numpy as np >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.where(a < 5, a, 10*a) array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
This can be used on multidimensional arrays too:
>>> np.where([[True, False], [True, True]], ... [[1, 2], [3, 4]], ... [[9, 8], [7, 6]]) array([[1, 8], [3, 4]])
The shapes of x, y, and the condition are broadcast together:
>>> x, y = np.ogrid[:3, :4] >>> np.where(x < y, x, 10 + y) # both x and 10+y are broadcast array([[10, 0, 0, 0], [10, 11, 1, 1], [10, 11, 12, 2]])
>>> a = np.array([[0, 1, 2], ... [0, 2, 4], ... [0, 3, 6]]) >>> np.where(a < 4, a, -1) # -1 is broadcast array([[ 0, 1, 2], [ 0, 2, -1], [ 0, 3, -1]])
- maximum = <ufunc 'maximum'>
- static clip(a, a_min=np._NoValue, a_max=np._NoValue, out=None, *, min=np._NoValue, max=np._NoValue, **kwargs)
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of
[0, 1]is specified, values smaller than 0 become 0, and values larger than 1 become 1.Equivalent to but faster than
np.minimum(a_max, np.maximum(a, a_min)).No check is performed to ensure
a_min < a_max.- Parameters:
a (array_like) – Array containing elements to clip.
a_min (array_like or None) – Minimum and maximum value. If
None, clipping is not performed on the corresponding edge. If botha_minanda_maxareNone, the elements of the returned array stay the same. Both are broadcasted againsta.a_max (array_like or None) – Minimum and maximum value. If
None, clipping is not performed on the corresponding edge. If botha_minanda_maxareNone, the elements of the returned array stay the same. Both are broadcasted againsta.out (ndarray, optional) – The results will be placed in this array. It may be the input array for in-place clipping. out must be of the right shape to hold the output. Its type is preserved.
min (array_like or None) –
Array API compatible alternatives for
a_minanda_maxarguments. Eithera_minanda_maxorminandmaxcan be passed at the same time. Default:None.Added in version 2.1.0.
max (array_like or None) –
Array API compatible alternatives for
a_minanda_maxarguments. Eithera_minanda_maxorminandmaxcan be passed at the same time. Default:None.Added in version 2.1.0.
**kwargs – For other keyword-only arguments, see the ufunc docs.
- Returns:
clipped_array – An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max.
- Return type:
ndarray
See also
Notes
When a_min is greater than a_max, clip returns an array in which all values are equal to a_max, as shown in the second example.
Examples
>>> import numpy as np >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, 1, 8) array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8]) >>> np.clip(a, 8, 1) array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) >>> np.clip(a, 3, 6, out=a) array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6]) >>> a array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6]) >>> a = np.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np.clip(a, [3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 8) array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
- floor = <ufunc 'floor'>
- isnan = <ufunc 'isnan'>
- isinf = <ufunc 'isinf'>
- sum(a, *args, dtype=None, **kwargs)[source]
Reduce with
np.sum, accumulating floats inaccumulator_dtypeby default.A float32
np.sumdrifts on large N; when the caller passes no explicitdtypewe promote floating inputs to the engine’s high-precision accumulator (float64) so correctness no longer relies on every caller threadingdtype=accumulator_dtype. Integer inputs and explicit-dtype calls keep NumPy’s default behavior.
- static max(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, where=np._NoValue)
Return the maximum of an array or maximum along an axis.
- Parameters:
a (array_like) – Input data.
axis (None or int or tuple of ints, optional) – Axis or axes along which to operate. By default, flattened input is used. If this is a tuple of ints, the maximum is selected over multiple axes, instead of a single axis or all the axes as before.
out (ndarray, optional) – Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See Output type determination for more details.
keepdims (bool, optional) –
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the
maxmethod of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.initial (scalar, optional) – The minimum value of an output element. Must be present to allow computation on empty slice. See ~numpy.ufunc.reduce for details.
where (array_like of bool, optional) – Elements to compare for the maximum. See ~numpy.ufunc.reduce for details.
- Returns:
max – Maximum of a. If axis is None, the result is a scalar value. If axis is an int, the result is an array of dimension
a.ndim - 1. If axis is a tuple, the result is an array of dimensiona.ndim - len(axis).- Return type:
ndarray or scalar
See also
minThe minimum value of an array along a given axis, propagating any NaNs.
nanmaxThe maximum value of an array along a given axis, ignoring any NaNs.
maximumElement-wise maximum of two arrays, propagating any NaNs.
fmaxElement-wise maximum of two arrays, ignoring any NaNs.
argmaxReturn the indices of the maximum values.
nanmin,minimum,fminNotes
NaN values are propagated, that is if at least one item is NaN, the corresponding max value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmax.
Don’t use ~numpy.max for element-wise comparison of 2 arrays; when
a.shape[0]is 2,maximum(a[0], a[1])is faster thanmax(a, axis=0).Examples
>>> import numpy as np >>> a = np.arange(4).reshape((2,2)) >>> a array([[0, 1], [2, 3]]) >>> np.max(a) # Maximum of the flattened array 3 >>> np.max(a, axis=0) # Maxima along the first axis array([2, 3]) >>> np.max(a, axis=1) # Maxima along the second axis array([1, 3]) >>> np.max(a, where=[False, True], initial=-1, axis=0) array([-1, 3]) >>> b = np.arange(5, dtype=np.float64) >>> b[2] = np.nan >>> np.max(b) np.float64(nan) >>> np.max(b, where=~np.isnan(b), initial=-1) 4.0 >>> np.nanmax(b) 4.0
You can use an initial value to compute the maximum of an empty slice, or to initialize it to a different value:
>>> np.max([[-50], [10]], axis=-1, initial=0) array([ 0, 10])
Notice that the initial value is used as one of the elements for which the maximum is determined, unlike for the default argument Python’s max function, which is only used for empty iterables.
>>> np.max([5], initial=6) 6 >>> max([5], default=6) 5
- static dot(a, b, out=None)
Dot product of two arrays. Specifically,
If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
If both a and b are 2-D arrays, it is matrix multiplication, but using
matmul()ora @ bis preferred.If either a or b is 0-D (scalar), it is equivalent to
multiply()and usingnumpy.multiply(a, b)ora * bis preferred.If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
If a is an N-D array and b is an M-D array (where
M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
It uses an optimized BLAS library when possible (see numpy.linalg).
- Parameters:
a (array_like) – First argument.
b (array_like) – Second argument.
out (ndarray, optional) – Output argument. This must have the exact kind that would be returned if it was not used. In particular, it must have the right type, must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b). This is a performance feature. Therefore, if these conditions are not met, an exception is raised, instead of attempting to be flexible.
- Returns:
output – Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.
- Return type:
ndarray
- Raises:
ValueError – If the last dimension of a is not the same size as the second-to-last dimension of b.
See also
vdotComplex-conjugating dot product.
vecdotVector dot product of two arrays.
tensordotSum products over arbitrary axes.
einsumEinstein summation convention.
matmul‘@’ operator as method with out parameter.
linalg.multi_dotChained dot product.
Examples
>>> import numpy as np >>> np.dot(3, 4) 12
Neither argument is complex-conjugated:
>>> np.dot([2j, 3j], [2j, 3j]) (-13+0j)
For 2-D arrays it is the matrix product:
>>> a = [[1, 0], [0, 1]] >>> b = [[4, 1], [2, 2]] >>> np.dot(a, b) array([[4, 1], [2, 2]])
>>> a = np.arange(3*4*5*6).reshape((3,4,5,6)) >>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3)) >>> np.dot(a, b)[2,3,2,1,2,2] 499128 >>> sum(a[2,3,2,:] * b[1,2,:,2]) 499128
- matmul = <ufunc 'matmul'>
- static cumsum(a, axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along a given axis.
- Parameters:
a (array_like) – Input array.
axis (int, optional) – Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
dtype (dtype, optional) – Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.
out (ndarray, optional) – Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. See Output type determination for more details.
- Returns:
cumsum_along_axis – A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.
- Return type:
ndarray.
See also
cumulative_sumArray API compatible alternative for
cumsum.sumSum array elements.
trapezoidIntegration of array values using composite trapezoidal rule.
diffCalculate the n-th discrete difference along given axis.
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
cumsum(a)[-1]may not be equal tosum(a)for floating-point values sincesummay use a pairwise summation routine, reducing the roundoff-error. See sum for more information.Examples
>>> import numpy as np >>> a = np.array([[1,2,3], [4,5,6]]) >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.cumsum(a) array([ 1, 3, 6, 10, 15, 21]) >>> np.cumsum(a, dtype=np.float64) # specifies type of output value(s) array([ 1., 3., 6., 10., 15., 21.])
>>> np.cumsum(a,axis=0) # sum over rows for each of the 3 columns array([[1, 2, 3], [5, 7, 9]]) >>> np.cumsum(a,axis=1) # sum over columns for each of the 2 rows array([[ 1, 3, 6], [ 4, 9, 15]])
cumsum(b)[-1]may not be equal tosum(b)>>> b = np.array([1, 2e-9, 3e-9] * 1000000) >>> b.cumsum()[-1] 1000000.0050045159 >>> b.sum() 1000000.0050000029
- static logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False)
Compute the log of the sum of exponentials of input elements.
- Parameters:
a (array_like) – Input array.
axis (None or int or tuple of ints, optional) –
Axis or axes over which the sum is taken. By default axis is None, and all elements are summed.
Added in version 0.11.0.
b (array-like, optional) –
Scaling factor for exp(a) must be of the same shape as a or broadcastable to a. These values may be negative in order to implement subtraction.
Added in version 0.12.0.
keepdims (bool, optional) –
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array.
Added in version 0.15.0.
return_sign (bool, optional) –
If this is set to True, the result will be a pair containing sign information; if False, results that are negative will be returned as NaN. Default is False (no sign information).
Added in version 0.16.0.
- Returns:
res (ndarray) – The result,
np.log(np.sum(np.exp(a)))calculated in a numerically more stable way. If b is given thennp.log(np.sum(b*np.exp(a)))is returned. Ifreturn_signis True,rescontains the log of the absolute value of the argument.sgn (ndarray) – If
return_signis True, this will be an array of floating-point numbers matching res containing +1, 0, -1 (for real-valued inputs) or a complex phase (for complex inputs). This gives the sign of the argument of the logarithm inres. Ifreturn_signis False, only one result is returned.
See also
Notes
NumPy has a logaddexp function which is very similar to logsumexp, but only handles two arguments. logaddexp.reduce is similar to this function, but may be less stable.
The logarithm is a multivalued function: for each \(x\) there is an infinite number of \(z\) such that \(exp(z) = x\). The convention is to return the \(z\) whose imaginary part lies in \((-pi, pi]\).
Array API Standard Support
logsumexp has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable
SCIPY_ARRAY_API=1and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following combinations of backend and device (or other capability) are supported.Library
CPU
GPU
NumPy
✅
n/a
CuPy
n/a
✅
PyTorch
✅
✅
JAX
✅
✅
Dask
✅
n/a
See Support for the array API standard for more information.
Examples
>>> import numpy as np >>> from scipy.special import logsumexp >>> a = np.arange(10) >>> logsumexp(a) 9.4586297444267107 >>> np.log(np.sum(np.exp(a))) 9.4586297444267107
With weights
>>> a = np.arange(10) >>> b = np.arange(10, 0, -1) >>> logsumexp(a, b=b) 9.9170178533034665 >>> np.log(np.sum(b*np.exp(a))) 9.9170178533034647
Returning a sign flag
>>> logsumexp([1,2],b=[1,-1],return_sign=True) (1.5413248546129181, -1.0)
Notice that logsumexp does not directly support masked arrays. To use it on a masked array, convert the mask into zero weights:
>>> a = np.ma.array([np.log(2), 2, np.log(3)], ... mask=[False, True, False]) >>> b = (~a.mask).astype(int) >>> logsumexp(a.data, b=b), np.log(5) 1.6094379124341005, 1.6094379124341005
- static bincount(x, /, weights=None, minlength=0)
Count number of occurrences of each value in array of non-negative ints.
The number of bins (of size 1) is one larger than the largest value in x. If minlength is specified, there will be at least this number of bins in the output array (though it will be longer if necessary, depending on the contents of x). Each bin gives the number of occurrences of its index value in x. If weights is specified the input array is weighted by it, i.e. if a value
nis found at positioni,out[n] += weight[i]instead ofout[n] += 1.- Parameters:
x (array_like, 1 dimension, nonnegative ints) – Input array.
weights (array_like, optional) – Weights, array of the same shape as x.
minlength (int, optional) – A minimum number of bins for the output array.
- Returns:
out – The result of binning the input array. The length of out is equal to
np.amax(x)+1.- Return type:
ndarray of ints
- Raises:
ValueError – If the input is not 1-dimensional, or contains elements with negative values, or if minlength is negative.
TypeError – If the type of the input is float or complex.
See also
histogram,digitize,uniqueExamples
>>> import numpy as np >>> np.bincount(np.arange(5)) array([1, 1, 1, 1, 1]) >>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])) array([1, 3, 1, 1, 0, 0, 0, 1])
>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23]) >>> np.bincount(x).size == np.amax(x)+1 True
The input array needs to be of integer dtype, otherwise a TypeError is raised:
>>> np.bincount(np.arange(5, dtype=np.float64)) Traceback (most recent call last): ... TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
A possible use of
bincountis to perform sums over variable-size chunks of an array, using theweightskeyword.>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights >>> x = np.array([0, 1, 1, 2, 2, 2]) >>> np.bincount(x, weights=w) array([ 0.3, 0.7, 1.1])
- static unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=True, sorted=True)
Find the unique elements of an array.
Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements:
the indices of the input array that give the unique values
the indices of the unique array that reconstruct the input array
the number of times each unique value comes up in the input array
- Parameters:
ar (array_like) – Input array. Unless axis is specified, this will be flattened if it is not already 1-D.
return_index (bool, optional) – If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array.
return_inverse (bool, optional) – If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct ar.
return_counts (bool, optional) – If True, also return the number of times each unique item appears in ar.
axis (int or None, optional) – The axis to operate on. If None, ar will be flattened. If an integer, the subarrays indexed by the given axis will be flattened and treated as the elements of a 1-D array with the dimension of the given axis, see the notes for more details. Object arrays or structured arrays that contain objects are not supported if the axis kwarg is used. The default is None.
equal_nan (bool, optional) –
If True, collapses multiple NaN values in the return array into one.
Added in version 1.24.
sorted (bool, optional) –
If True, the unique elements are sorted. Elements may be sorted in practice even if
sorted=False, but this could change without notice.Added in version 2.3.
- Returns:
unique (ndarray) – The sorted unique values.
unique_indices (ndarray, optional) – The indices of the first occurrences of the unique values in the original array. Only provided if return_index is True.
unique_inverse (ndarray, optional) – The indices to reconstruct the original array from the unique array. Only provided if return_inverse is True.
unique_counts (ndarray, optional) – The number of times each of the unique values comes up in the original array. Only provided if return_counts is True.
See also
repeatRepeat elements of an array.
sortReturn a sorted copy of an array.
Notes
When an axis is specified the subarrays indexed by the axis are sorted. This is done by making the specified axis the first dimension of the array (move the axis to the first dimension to keep the order of the other axes) and then flattening the subarrays in C order. The flattened subarrays are then viewed as a structured type with each element given a label, with the effect that we end up with a 1-D array of structured types that can be treated in the same way as any other 1-D array. The result is that the flattened subarrays are sorted in lexicographic order starting with the first element.
Changed in version 1.21: Like np.sort, NaN will sort to the end of the values. For complex arrays all NaN values are considered equivalent (no matter whether the NaN is in the real or imaginary part). As the representant for the returned array the smallest one in the lexicographical order is chosen - see np.sort for how the lexicographical order is defined for complex arrays.
Changed in version 2.0: For multi-dimensional inputs,
unique_inverseis reshaped such that the input can be reconstructed usingnp.take(unique, unique_inverse, axis=axis). The result is now not 1-dimensional whenaxis=None.Note that in NumPy 2.0.0 a higher dimensional array was returned also when
axiswas notNone. This was reverted, butinverse.reshape(-1)can be used to ensure compatibility with both versions.Examples
>>> import numpy as np >>> np.unique([1, 1, 2, 2, 3, 3]) array([1, 2, 3]) >>> a = np.array([[1, 1], [2, 3]]) >>> np.unique(a) array([1, 2, 3])
Return the unique rows of a 2D array
>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) >>> np.unique(a, axis=0) array([[1, 0, 0], [2, 3, 4]])
Return the indices of the original array that give the unique values:
>>> a = np.array(['a', 'b', 'b', 'c', 'a']) >>> u, indices = np.unique(a, return_index=True) >>> u array(['a', 'b', 'c'], dtype='<U1') >>> indices array([0, 1, 3]) >>> a[indices] array(['a', 'b', 'c'], dtype='<U1')
Reconstruct the input array from the unique values and inverse:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> u, indices = np.unique(a, return_inverse=True) >>> u array([1, 2, 3, 4, 6]) >>> indices array([0, 1, 4, 3, 1, 2, 1]) >>> u[indices] array([1, 2, 6, 4, 2, 3, 2])
Reconstruct the input values from the unique values and counts:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> values, counts = np.unique(a, return_counts=True) >>> values array([1, 2, 3, 4, 6]) >>> counts array([1, 3, 1, 1, 1]) >>> np.repeat(values, counts) array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved
- static searchsorted(a, v, side='left', sorter=None)
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved.
Assuming that a is sorted:
side
returned index i satisfies
left
a[i-1] < v <= a[i]right
a[i-1] <= v < a[i]- Parameters:
a (1-D array_like) – Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it.
v (array_like) – Values to insert into a.
side ({'left', 'right'}, optional) – If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a).
sorter (1-D array_like, optional) – Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort.
- Returns:
indices – Array of insertion points with the same shape as v, or an integer if v is a scalar.
- Return type:
int or array of ints
See also
sortReturn a sorted copy of an array.
histogramProduce histogram from 1-D data.
Notes
Binary search is used to find the required insertion points.
As of NumPy 1.4.0 searchsorted works with real/complex arrays containing nan values. The enhanced sort order is documented in sort.
This function uses the same algorithm as the builtin python bisect.bisect_left (
side='left') and bisect.bisect_right (side='right') functions, which is also vectorized in the v argument.Examples
>>> import numpy as np >>> np.searchsorted([11,12,13,14,15], 13) 2 >>> np.searchsorted([11,12,13,14,15], 13, side='right') 3 >>> np.searchsorted([11,12,13,14,15], [-10, 20, 12, 13]) array([0, 5, 1, 2])
When sorter is used, the returned indices refer to the sorted array of a and not a itself:
>>> a = np.array([40, 10, 20, 30]) >>> sorter = np.argsort(a) >>> sorter array([1, 2, 3, 0]) # Indices that would sort the array 'a' >>> result = np.searchsorted(a, 25, sorter=sorter) >>> result 2 >>> a[sorter[result]] 30 # The element at index 2 of the sorted array is 30.
- gammaln = <ufunc 'gammaln'>
- digamma = <ufunc 'psi'>
- betaln = <ufunc 'betaln'>
- erf = <ufunc 'erf'>
- cos = <ufunc 'cos'>
- sin = <ufunc 'sin'>
- arctan2 = <ufunc 'arctan2'>
- i0e = <ufunc 'i0e'>
- erfcx = <ufunc 'erfcx'>