doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.base_repr numpy.base_repr(number, base=2, padding=0)[source] Return a string representation of a number in the given base system. Parameters numberint The value to convert. Positive and negative values are handled. baseint, optional Convert number to the base number system. The valid range is 2-36, the default value is 2. paddingint, optional Number of zeros padded on the left. Default is 0 (no padding). Returns outstr String representation of number in base system. See also binary_repr Faster version of base_repr for base 2. Examples >>> np.base_repr(5) '101' >>> np.base_repr(6, 5) '11' >>> np.base_repr(7, base=5, padding=3) '00012' >>> np.base_repr(10, base=16) 'A' >>> np.base_repr(32, base=16) '20'
numpy.reference.generated.numpy.base_repr
numpy.binary_repr numpy.binary_repr(num, width=None)[source] Return the binary representation of the input number as a string. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the two’s complement of the number is returned, with respect to that width. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value. This is the most common method of representing signed integers on computers [1]. A N-bit two’s-complement system can represent every integer in the range \(-2^{N-1}\) to \(+2^{N-1}-1\). Parameters numint Only an integer decimal number can be used. widthint, optional The length of the returned string if num is positive, or the length of the two’s complement if num is negative, provided that width is at least a sufficient number of bits for num to be represented in the designated form. If the width value is insufficient, it will be ignored, and num will be returned in binary (num > 0) or two’s complement (num < 0) form with its width equal to the minimum number of bits needed to represent the number in the designated form. This behavior is deprecated and will later raise an error. Deprecated since version 1.12.0. Returns binstr Binary representation of num or two’s complement of num. See also base_repr Return a string representation of a number in the given base system. bin Python’s built-in binary representation generator of an integer. Notes binary_repr is equivalent to using base_repr with base 2, but about 25x faster. References 1 Wikipedia, “Two’s complement”, https://en.wikipedia.org/wiki/Two’s_complement Examples >>> np.binary_repr(3) '11' >>> np.binary_repr(-3) '-11' >>> np.binary_repr(3, width=4) '0011' The two’s complement is returned when the input number is negative and width is specified: >>> np.binary_repr(-3, width=3) '101' >>> np.binary_repr(-3, width=5) '11101'
numpy.reference.generated.numpy.binary_repr
numpy.bincount numpy.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 n is found at position i, out[n] += weight[i] instead of out[n] += 1. Parameters xarray_like, 1 dimension, nonnegative ints Input array. weightsarray_like, optional Weights, array of the same shape as x. minlengthint, optional A minimum number of bins for the output array. New in version 1.6.0. Returns outndarray of ints The result of binning the input array. The length of out is equal to np.amax(x)+1. 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, unique Examples >>> 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=float)) 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 bincount is to perform sums over variable-size chunks of an array, using the weights keyword. >>> 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])
numpy.reference.generated.numpy.bincount
numpy.bitwise_and numpy.bitwise_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'bitwise_and'> Compute the bit-wise AND of two arrays element-wise. Computes the bit-wise AND of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator &. Parameters x1, x2array_like Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Result. This is a scalar if both x1 and x2 are scalars. See also logical_and bitwise_or bitwise_xor binary_repr Return the binary representation of the input number as a string. Examples The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise AND of 13 and 17 is therefore 000000001, or 1: >>> np.bitwise_and(13, 17) 1 >>> np.bitwise_and(14, 13) 12 >>> np.binary_repr(12) '1100' >>> np.bitwise_and([14,3], 13) array([12, 1]) >>> np.bitwise_and([11,7], [4,25]) array([0, 1]) >>> np.bitwise_and(np.array([2,5,255]), np.array([3,14,16])) array([ 2, 4, 16]) >>> np.bitwise_and([True, True], [False, True]) array([False, True]) The & operator can be used as a shorthand for np.bitwise_and on ndarrays. >>> x1 = np.array([2, 5, 255]) >>> x2 = np.array([3, 14, 16]) >>> x1 & x2 array([ 2, 4, 16])
numpy.reference.generated.numpy.bitwise_and
numpy.bitwise_or numpy.bitwise_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'bitwise_or'> Compute the bit-wise OR of two arrays element-wise. Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator |. Parameters x1, x2array_like Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Result. This is a scalar if both x1 and x2 are scalars. See also logical_or bitwise_and bitwise_xor binary_repr Return the binary representation of the input number as a string. Examples The number 13 has the binary representation 00001101. Likewise, 16 is represented by 00010000. The bit-wise OR of 13 and 16 is then 000111011, or 29: >>> np.bitwise_or(13, 16) 29 >>> np.binary_repr(29) '11101' >>> np.bitwise_or(32, 2) 34 >>> np.bitwise_or([33, 4], 1) array([33, 5]) >>> np.bitwise_or([33, 4], [1, 2]) array([33, 6]) >>> np.bitwise_or(np.array([2, 5, 255]), np.array([4, 4, 4])) array([ 6, 5, 255]) >>> np.array([2, 5, 255]) | np.array([4, 4, 4]) array([ 6, 5, 255]) >>> np.bitwise_or(np.array([2, 5, 255, 2147483647], dtype=np.int32), ... np.array([4, 4, 4, 2147483647], dtype=np.int32)) array([ 6, 5, 255, 2147483647]) >>> np.bitwise_or([True, True], [False, True]) array([ True, True]) The | operator can be used as a shorthand for np.bitwise_or on ndarrays. >>> x1 = np.array([2, 5, 255]) >>> x2 = np.array([4, 4, 4]) >>> x1 | x2 array([ 6, 5, 255])
numpy.reference.generated.numpy.bitwise_or
numpy.bitwise_xor numpy.bitwise_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'bitwise_xor'> Compute the bit-wise XOR of two arrays element-wise. Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ^. Parameters x1, x2array_like Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Result. This is a scalar if both x1 and x2 are scalars. See also logical_xor bitwise_and bitwise_or binary_repr Return the binary representation of the input number as a string. Examples The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise XOR of 13 and 17 is therefore 00011100, or 28: >>> np.bitwise_xor(13, 17) 28 >>> np.binary_repr(28) '11100' >>> np.bitwise_xor(31, 5) 26 >>> np.bitwise_xor([31,3], 5) array([26, 6]) >>> np.bitwise_xor([31,3], [5,6]) array([26, 5]) >>> np.bitwise_xor([True, True], [False, True]) array([ True, False]) The ^ operator can be used as a shorthand for np.bitwise_xor on ndarrays. >>> x1 = np.array([True, True]) >>> x2 = np.array([False, True]) >>> x1 ^ x2 array([ True, False])
numpy.reference.generated.numpy.bitwise_xor
numpy.blackman numpy.blackman(M)[source] Return the Blackman window. The Blackman window is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window. Parameters Mint Number of points in the output window. If zero or less, an empty array is returned. Returns outndarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See also bartlett, hamming, hanning, kaiser Notes The Blackman window is defined as \[w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)\] Most references to the Blackman window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means “removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It is known as a “near optimal” tapering function, almost as good (by some measures) as the kaiser window. References Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York. Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471. Examples >>> import matplotlib.pyplot as plt >>> np.blackman(12) array([-1.38777878e-17, 3.26064346e-02, 1.59903635e-01, # may vary 4.14397981e-01, 7.36045180e-01, 9.67046769e-01, 9.67046769e-01, 7.36045180e-01, 4.14397981e-01, 1.59903635e-01, 3.26064346e-02, -1.38777878e-17]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.blackman(51) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Blackman window") Text(0.5, 1.0, 'Blackman window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show() >>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> with np.errstate(divide='ignore', invalid='ignore'): ... response = 20 * np.log10(mag) ... >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Blackman window") Text(0.5, 1.0, 'Frequency response of Blackman window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> _ = plt.axis('tight') >>> plt.show()
numpy.reference.generated.numpy.blackman
numpy.block numpy.block(arrays)[source] Assemble an nd-array from nested lists of blocks. Blocks in the innermost lists are concatenated (see concatenate) along the last dimension (-1), then these are concatenated along the second-last dimension (-2), and so on until the outermost list is reached. Blocks can be of any dimension, but will not be broadcasted using the normal rules. Instead, leading axes of size 1 are inserted, to make block.ndim the same for all blocks. This is primarily useful for working with scalars, and means that code like np.block([v, 1]) is valid, where v.ndim == 1. When the nested list is two levels deep, this allows block matrices to be constructed from their components. New in version 1.13.0. Parameters arraysnested list of array_like or scalars (but not tuples) If passed a single ndarray or scalar (a nested list of depth 0), this is returned unmodified (and not copied). Elements shapes must match along the appropriate axes (without broadcasting), but leading 1s will be prepended to the shape as necessary to make the dimensions match. Returns block_arrayndarray The array assembled from the given blocks. The dimensionality of the output is equal to the greatest of: * the dimensionality of all the inputs * the depth to which the input list is nested Raises ValueError If list depths are mismatched - for instance, [[a, b], c] is illegal, and should be spelt [[a, b], [c]] If lists are empty - for instance, [[a, b], []] See also concatenate Join a sequence of arrays along an existing axis. stack Join a sequence of arrays along a new axis. vstack Stack arrays in sequence vertically (row wise). hstack Stack arrays in sequence horizontally (column wise). dstack Stack arrays in sequence depth wise (along third axis). column_stack Stack 1-D arrays as columns into a 2-D array. vsplit Split an array into multiple sub-arrays vertically (row-wise). Notes When called with only scalars, np.block is equivalent to an ndarray call. So np.block([[1, 2], [3, 4]]) is equivalent to np.array([[1, 2], [3, 4]]). This function does not enforce that the blocks lie on a fixed grid. np.block([[a, b], [c, d]]) is not restricted to arrays of the form: AAAbb AAAbb cccDD But is also allowed to produce, for some a, b, c, d: AAAbb AAAbb cDDDD Since concatenation happens along the last axis first, block is _not_ capable of producing the following directly: AAAbb cccbb cccDD Matlab’s “square bracket stacking”, [A, B, ...; p, q, ...], is equivalent to np.block([[A, B, ...], [p, q, ...]]). Examples The most common use of this function is to build a block matrix >>> A = np.eye(2) * 2 >>> B = np.eye(3) * 3 >>> np.block([ ... [A, np.zeros((2, 3))], ... [np.ones((3, 2)), B ] ... ]) array([[2., 0., 0., 0., 0.], [0., 2., 0., 0., 0.], [1., 1., 3., 0., 0.], [1., 1., 0., 3., 0.], [1., 1., 0., 0., 3.]]) With a list of depth 1, block can be used as hstack >>> np.block([1, 2, 3]) # hstack([1, 2, 3]) array([1, 2, 3]) >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.block([a, b, 10]) # hstack([a, b, 10]) array([ 1, 2, 3, 4, 5, 6, 10]) >>> A = np.ones((2, 2), int) >>> B = 2 * A >>> np.block([A, B]) # hstack([A, B]) array([[1, 1, 2, 2], [1, 1, 2, 2]]) With a list of depth 2, block can be used in place of vstack: >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.block([[a], [b]]) # vstack([a, b]) array([[1, 2, 3], [4, 5, 6]]) >>> A = np.ones((2, 2), int) >>> B = 2 * A >>> np.block([[A], [B]]) # vstack([A, B]) array([[1, 1], [1, 1], [2, 2], [2, 2]]) It can also be used in places of atleast_1d and atleast_2d >>> a = np.array(0) >>> b = np.array([1]) >>> np.block([a]) # atleast_1d(a) array([0]) >>> np.block([b]) # atleast_1d(b) array([1]) >>> np.block([[a]]) # atleast_2d(a) array([[0]]) >>> np.block([[b]]) # atleast_2d(b) array([[1]])
numpy.reference.generated.numpy.block
numpy.bmat numpy.bmat(obj, ldict=None, gdict=None)[source] Build a matrix object from a string, nested sequence, or array. Parameters objstr or array_like Input data. If a string, variables in the current scope may be referenced by name. ldictdict, optional A dictionary that replaces local operands in current frame. Ignored if obj is not a string or gdict is None. gdictdict, optional A dictionary that replaces global operands in current frame. Ignored if obj is not a string. Returns outmatrix Returns a matrix object, which is a specialized 2-D array. See also block A generalization of this function for N-d arrays, that returns normal ndarrays. Examples >>> A = np.mat('1 1; 1 1') >>> B = np.mat('2 2; 2 2') >>> C = np.mat('3 4; 5 6') >>> D = np.mat('7 8; 9 0') All the following expressions construct the same block matrix: >>> np.bmat([[A, B], [C, D]]) matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) >>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]]) matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]]) >>> np.bmat('A,B; C,D') matrix([[1, 1, 2, 2], [1, 1, 2, 2], [3, 4, 7, 8], [5, 6, 9, 0]])
numpy.reference.generated.numpy.bmat
numpy.broadcast class numpy.broadcast[source] Produce an object that mimics broadcasting. Parameters in1, in2, …array_like Input parameters. Returns bbroadcast object Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has shape and nd properties, and may be used as an iterator. See also broadcast_arrays broadcast_to broadcast_shapes Examples Manually adding two vectors, using broadcasting: >>> x = np.array([[1], [2], [3]]) >>> y = np.array([4, 5, 6]) >>> b = np.broadcast(x, y) >>> out = np.empty(b.shape) >>> out.flat = [u+v for (u,v) in b] >>> out array([[5., 6., 7.], [6., 7., 8.], [7., 8., 9.]]) Compare against built-in broadcasting: >>> x + y array([[5, 6, 7], [6, 7, 8], [7, 8, 9]]) Attributes index current index in broadcasted result iters tuple of iterators along self’s “components.” nd Number of dimensions of broadcasted result. ndim Number of dimensions of broadcasted result. numiter Number of iterators possessed by the broadcasted result. shape Shape of broadcasted result. size Total size of broadcasted result. Methods reset() Reset the broadcasted result's iterator(s).
numpy.reference.generated.numpy.broadcast
numpy.broadcast_arrays numpy.broadcast_arrays(*args, subok=False)[source] Broadcast any number of arrays against each other. Parameters `*args`array_likes The arrays to broadcast. subokbool, optional If True, then sub-classes will be passed-through, otherwise the returned arrays will be forced to be a base-class array (default). Returns broadcastedlist of arrays These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first. While you can set the writable flag True, writing to a single output value may end up changing more than one location in the output array. Deprecated since version 1.17: The output is currently marked so that if written to, a deprecation warning will be emitted. A future version will set the writable flag False so writing to it will raise an error. See also broadcast broadcast_to broadcast_shapes Examples >>> x = np.array([[1,2,3]]) >>> y = np.array([[4],[5]]) >>> np.broadcast_arrays(x, y) [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])] Here is a useful idiom for getting contiguous copies instead of non-contiguous views. >>> [np.array(a) for a in np.broadcast_arrays(x, y)] [array([[1, 2, 3], [1, 2, 3]]), array([[4, 4, 4], [5, 5, 5]])]
numpy.reference.generated.numpy.broadcast_arrays
numpy.broadcast_shapes numpy.broadcast_shapes(*args)[source] Broadcast the input shapes into a single shape. Learn more about broadcasting here. New in version 1.20.0. Parameters `*args`tuples of ints, or ints The shapes to be broadcast against each other. Returns tuple Broadcasted shape. Raises ValueError If the shapes are not compatible and cannot be broadcast according to NumPy’s broadcasting rules. See also broadcast broadcast_arrays broadcast_to Examples >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2)) (3, 2) >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7)) (5, 6, 7)
numpy.reference.generated.numpy.broadcast_shapes
numpy.broadcast_to numpy.broadcast_to(array, shape, subok=False)[source] Broadcast an array to a new shape. Parameters arrayarray_like The array to broadcast. shapetuple or int The shape of the desired array. A single integer i is interpreted as (i,). subokbool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). Returns broadcastarray A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. Raises ValueError If the array is not compatible with the new shape according to NumPy’s broadcasting rules. See also broadcast broadcast_arrays broadcast_shapes Notes New in version 1.10.0. Examples >>> x = np.array([1, 2, 3]) >>> np.broadcast_to(x, (3, 3)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
numpy.reference.generated.numpy.broadcast_to
numpy.busday_count numpy.busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None) Counts the number of valid days between begindates and enddates, not including the day of enddates. If enddates specifies a date value that is earlier than the corresponding begindates date value, the count will be negative. New in version 1.7.0. Parameters begindatesarray_like of datetime64[D] The array of the first dates for counting. enddatesarray_like of datetime64[D] The array of the end dates for counting, which are excluded from the count themselves. weekmaskstr or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like ‘1111100’; or a string like “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidaysarray_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycalbusdaycalendar, optional A busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. outarray of int, optional If provided, this array is filled with the result. Returns outarray of int An array with a shape from broadcasting begindates and enddates together, containing the number of valid days between the begin and end dates. See also busdaycalendar An object that specifies a custom set of valid days. is_busday Returns a boolean array indicating valid days. busday_offset Applies an offset counted in valid days. Examples >>> # Number of weekdays in January 2011 ... np.busday_count('2011-01', '2011-02') 21 >>> # Number of weekdays in 2011 >>> np.busday_count('2011', '2012') 260 >>> # Number of Saturdays in 2011 ... np.busday_count('2011', '2012', weekmask='Sat') 53
numpy.reference.generated.numpy.busday_count
numpy.busday_offset numpy.busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None) First adjusts the date to fall on a valid day according to the roll rule, then applies offsets to the given dates counted in valid days. New in version 1.7.0. Parameters datesarray_like of datetime64[D] The array of dates to process. offsetsarray_like of int The array of offsets, which is broadcast with dates. roll{‘raise’, ‘nat’, ‘forward’, ‘following’, ‘backward’, ‘preceding’, ‘modifiedfollowing’, ‘modifiedpreceding’}, optional How to treat dates that do not fall on a valid day. The default is ‘raise’. ‘raise’ means to raise an exception for an invalid day. ‘nat’ means to return a NaT (not-a-time) for an invalid day. ‘forward’ and ‘following’ mean to take the first valid day later in time. ‘backward’ and ‘preceding’ mean to take the first valid day earlier in time. ‘modifiedfollowing’ means to take the first valid day later in time unless it is across a Month boundary, in which case to take the first valid day earlier in time. ‘modifiedpreceding’ means to take the first valid day earlier in time unless it is across a Month boundary, in which case to take the first valid day later in time. weekmaskstr or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like ‘1111100’; or a string like “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidaysarray_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycalbusdaycalendar, optional A busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. outarray of datetime64[D], optional If provided, this array is filled with the result. Returns outarray of datetime64[D] An array with a shape from broadcasting dates and offsets together, containing the dates with offsets applied. See also busdaycalendar An object that specifies a custom set of valid days. is_busday Returns a boolean array indicating valid days. busday_count Counts how many valid days are in a half-open date range. Examples >>> # First business day in October 2011 (not accounting for holidays) ... np.busday_offset('2011-10', 0, roll='forward') numpy.datetime64('2011-10-03') >>> # Last business day in February 2012 (not accounting for holidays) ... np.busday_offset('2012-03', -1, roll='forward') numpy.datetime64('2012-02-29') >>> # Third Wednesday in January 2011 ... np.busday_offset('2011-01', 2, roll='forward', weekmask='Wed') numpy.datetime64('2011-01-19') >>> # 2012 Mother's Day in Canada and the U.S. ... np.busday_offset('2012-05', 1, roll='forward', weekmask='Sun') numpy.datetime64('2012-05-13') >>> # First business day on or after a date ... np.busday_offset('2011-03-20', 0, roll='forward') numpy.datetime64('2011-03-21') >>> np.busday_offset('2011-03-22', 0, roll='forward') numpy.datetime64('2011-03-22') >>> # First business day after a date ... np.busday_offset('2011-03-20', 1, roll='backward') numpy.datetime64('2011-03-21') >>> np.busday_offset('2011-03-22', 1, roll='backward') numpy.datetime64('2011-03-23')
numpy.reference.generated.numpy.busday_offset
numpy.busdaycalendar class numpy.busdaycalendar(weekmask='1111100', holidays=None)[source] A business day calendar object that efficiently stores information defining valid days for the busday family of functions. The default valid days are Monday through Friday (“business days”). A busdaycalendar object can be specified with any set of weekly valid days, plus an optional “holiday” dates that always will be invalid. Once a busdaycalendar object is created, the weekmask and holidays cannot be modified. New in version 1.7.0. Parameters weekmaskstr or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like ‘1111100’; or a string like “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidaysarray_like of datetime64[D], optional An array of dates to consider as invalid dates, no matter which weekday they fall upon. Holiday dates may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. Returns outbusdaycalendar A business day calendar object containing the specified weekmask and holidays values. See also is_busday Returns a boolean array indicating valid days. busday_offset Applies an offset counted in valid days. busday_count Counts how many valid days are in a half-open date range. Examples >>> # Some important days in July ... bdd = np.busdaycalendar( ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) >>> # Default is Monday to Friday weekdays ... bdd.weekmask array([ True, True, True, True, True, False, False]) >>> # Any holidays already on the weekend are removed ... bdd.holidays array(['2011-07-01', '2011-07-04'], dtype='datetime64[D]') Attributes Note: once a busdaycalendar object is created, you cannot modify the weekmask or holidays. The attributes return copies of internal data. weekmask(copy) seven-element array of bool A copy of the seven-element boolean mask indicating valid days. holidays(copy) sorted array of datetime64[D] A copy of the holiday array indicating additional invalid days.
numpy.reference.generated.numpy.busdaycalendar
class numpy.byte[source] Signed integer type, compatible with C char. Character code 'b' Alias on this platform (Linux x86_64) numpy.int8: 8-bit signed integer (-128 to 127).
numpy.reference.arrays.scalars#numpy.byte
numpy.byte_bounds numpy.byte_bounds(a)[source] Returns pointers to the end-points of an array. Parameters andarray Input array. It must conform to the Python-side of the array interface. Returns (low, high)tuple of 2 integers The first integer is the first byte of the array, the second integer is just past the last byte of the array. If a is not contiguous it will not use every byte between the (low, high) values. Examples >>> I = np.eye(2, dtype='f'); I.dtype dtype('float32') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True >>> I = np.eye(2); I.dtype dtype('float64') >>> low, high = np.byte_bounds(I) >>> high - low == I.size*I.itemsize True
numpy.reference.generated.numpy.byte_bounds
class numpy.bytes_[source] A byte string. When used in arrays, this type strips trailing null bytes. Character code 'S' Alias numpy.string_
numpy.reference.arrays.scalars#numpy.bytes_
numpy.c_ numpy.c_ = <numpy.lib.index_tricks.CClass object> Translates slice objects to concatenation along the second axis. This is short-hand for np.r_['-1,2,0', index expression], which is useful because of its common occurrence. In particular, arrays will be stacked along their last axis after being upgraded to at least 2-D with 1’s post-pended to the shape (column vectors made out of 1-D arrays). See also column_stack Stack 1-D arrays as columns into a 2-D array. r_ For more detailed documentation. Examples >>> np.c_[np.array([1,2,3]), np.array([4,5,6])] array([[1, 4], [2, 5], [3, 6]]) >>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])] array([[1, 2, 3, ..., 4, 5, 6]])
numpy.reference.generated.numpy.c_
numpy.can_cast numpy.can_cast(from_, to, casting='safe') Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer. Parameters from_dtype, dtype specifier, scalar, or array Data type, scalar, or array to cast from. todtype or dtype specifier Data type to cast to. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional Controls what kind of data casting may occur. ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done. Returns outbool True if cast can occur according to the casting rule. See also dtype, result_type Notes Changed in version 1.17.0: Casting between a simple data type and a structured one is possible only for “unsafe” casting. Casting to multiple fields is allowed, but casting from multiple fields is not. Changed in version 1.9.0: Casting from numeric to string types in ‘safe’ casting mode requires that the string dtype length is long enough to store the maximum integer/float value converted. Examples Basic examples >>> np.can_cast(np.int32, np.int64) True >>> np.can_cast(np.float64, complex) True >>> np.can_cast(complex, float) False >>> np.can_cast('i8', 'f8') True >>> np.can_cast('i8', 'f4') False >>> np.can_cast('i4', 'S4') False Casting scalars >>> np.can_cast(100, 'i1') True >>> np.can_cast(150, 'i1') False >>> np.can_cast(150, 'u1') True >>> np.can_cast(3.5e100, np.float32) False >>> np.can_cast(1000.0, np.float32) True Array scalar checks the value, array does not >>> np.can_cast(np.array(1000.0), np.float32) True >>> np.can_cast(np.array([1000.0]), np.float32) False Using the casting rules >>> np.can_cast('i8', 'i8', 'no') True >>> np.can_cast('<i8', '>i8', 'no') False >>> np.can_cast('<i8', '>i8', 'equiv') True >>> np.can_cast('<i4', '>i8', 'equiv') False >>> np.can_cast('<i4', '>i8', 'safe') True >>> np.can_cast('<i8', '>i4', 'safe') False >>> np.can_cast('<i8', '>i4', 'same_kind') True >>> np.can_cast('<i8', '>u4', 'same_kind') False >>> np.can_cast('<i8', '>u4', 'unsafe') True
numpy.reference.generated.numpy.can_cast
numpy.cbrt numpy.cbrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'cbrt'> Return the cube-root of an array, element-wise. New in version 1.10.0. Parameters xarray_like The values whose cube-roots are required. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray An array of the same shape as x, containing the cube cube-root of each element in x. If out was provided, y is a reference to it. This is a scalar if x is a scalar. Examples >>> np.cbrt([1,8,27]) array([ 1., 2., 3.])
numpy.reference.generated.numpy.cbrt
class numpy.cdouble(real=0, imag=0)[source] Complex number type composed of two double-precision floating-point numbers, compatible with Python complex. Character code 'D' Alias numpy.cfloat Alias numpy.complex_ Alias on this platform (Linux x86_64) numpy.complex128: Complex number type composed of 2 64-bit-precision floating-point numbers.
numpy.reference.arrays.scalars#numpy.cdouble
numpy.ceil numpy.ceil(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'ceil'> Return the ceiling of the input, element-wise. The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \(\lceil x \rceil\). Parameters xarray_like Input data. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray or scalar The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar. See also floor, trunc, rint, fix Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.ceil(a) array([-1., -1., -0., 1., 2., 2., 2.])
numpy.reference.generated.numpy.ceil
numpy.cfloat[source] alias of numpy.cdouble
numpy.reference.arrays.scalars#numpy.cfloat
numpy.char.chararray class numpy.char.chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order=None)[source] Provides a convenient view on arrays of string and unicode values. Note The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations. Versus a regular NumPy array of type str or unicode, this class adds the following functionality: values automatically have whitespace removed from the end when indexed comparison operators automatically remove whitespace from the end when comparing values vectorized string operations are provided as methods (e.g. endswith) and infix operators (e.g. "+", "*", "%") chararrays should be created using numpy.char.array or numpy.char.asarray, rather than this constructor directly. This constructor creates the array, using buffer (with offset and strides) if it is not None. If buffer is None, then constructs a new array with strides in “C order”, unless both len(shape) >= 2 and order='F', in which case strides is in “Fortran order”. Parameters shapetuple Shape of the array. itemsizeint, optional Length of each array element, in number of characters. Default is 1. unicodebool, optional Are the array elements of type unicode (True) or string (False). Default is False. bufferobject exposing the buffer interface or str, optional Memory address of the start of the array data. Default is None, in which case a new array is created. offsetint, optional Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0. stridesarray_like of ints, optional Strides for the array (see ndarray.strides for full description). Default is None. order{‘C’, ‘F’}, optional The order in which the array data is stored in memory: ‘C’ -> “row major” order (the default), ‘F’ -> “column major” (Fortran) order. Examples >>> charar = np.chararray((3, 3)) >>> charar[:] = 'a' >>> charar chararray([[b'a', b'a', b'a'], [b'a', b'a', b'a'], [b'a', b'a', b'a']], dtype='|S1') >>> charar = np.chararray(charar.shape, itemsize=5) >>> charar[:] = 'abc' >>> charar chararray([[b'abc', b'abc', b'abc'], [b'abc', b'abc', b'abc'], [b'abc', b'abc', b'abc']], dtype='|S5') Attributes T The transposed array. base Base object if memory is from some other object. ctypes An object to simplify the interaction of the array with the ctypes module. data Python buffer object pointing to the start of the array’s data. dtype Data-type of the array’s elements. flags Information about the memory layout of the array. flat A 1-D iterator over the array. imag The imaginary part of the array. itemsize Length of one array element in bytes. nbytes Total bytes consumed by the elements of the array. ndim Number of array dimensions. real The real part of the array. shape Tuple of array dimensions. size Number of elements in the array. strides Tuple of bytes to step in each dimension when traversing an array. Methods astype(dtype[, order, casting, subok, copy]) Copy of the array, cast to a specified type. argsort([axis, kind, order]) Returns the indices that would sort this array. copy([order]) Return a copy of the array. count(sub[, start, end]) Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end]. decode([encoding, errors]) Calls str.decode element-wise. dump(file) Dump a pickle of the array to the specified file. dumps() Returns the pickle of the array as a string. encode([encoding, errors]) Calls str.encode element-wise. endswith(suffix[, start, end]) Returns a boolean array which is True where the string element in self ends with suffix, otherwise False. expandtabs([tabsize]) Return a copy of each string element where all tab characters are replaced by one or more spaces. fill(value) Fill the array with a scalar value. find(sub[, start, end]) For each element, return the lowest index in the string where substring sub is found. flatten([order]) Return a copy of the array collapsed into one dimension. getfield(dtype[, offset]) Returns a field of the given array as a certain type. index(sub[, start, end]) Like find, but raises ValueError when the substring is not found. isalnum() Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. isalpha() Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. isdecimal() For each element in self, return True if there are only decimal characters in the element. isdigit() Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. islower() Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. isnumeric() For each element in self, return True if there are only numeric characters in the element. isspace() Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. istitle() Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. isupper() Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. item(*args) Copy an element of an array to a standard Python scalar and return it. join(seq) Return a string which is the concatenation of the strings in the sequence seq. ljust(width[, fillchar]) Return an array with the elements of self left-justified in a string of length width. lower() Return an array with the elements of self converted to lowercase. lstrip([chars]) For each element in self, return a copy with the leading characters removed. nonzero() Return the indices of the elements that are non-zero. put(indices, values[, mode]) Set a.flat[n] = values[n] for all n in indices. ravel([order]) Return a flattened array. repeat(repeats[, axis]) Repeat elements of an array. replace(old, new[, count]) For each element in self, return a copy of the string with all occurrences of substring old replaced by new. reshape(shape[, order]) Returns an array containing the same data with a new shape. resize(new_shape[, refcheck]) Change shape and size of array in-place. rfind(sub[, start, end]) For each element in self, return the highest index in the string where substring sub is found, such that sub is contained within [start, end]. rindex(sub[, start, end]) Like rfind, but raises ValueError when the substring sub is not found. rjust(width[, fillchar]) Return an array with the elements of self right-justified in a string of length width. rsplit([sep, maxsplit]) For each element in self, return a list of the words in the string, using sep as the delimiter string. rstrip([chars]) For each element in self, return a copy with the trailing characters removed. searchsorted(v[, side, sorter]) Find indices where elements of v should be inserted in a to maintain order. setfield(val, dtype[, offset]) Put a value into a specified place in a field defined by a data-type. setflags([write, align, uic]) Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. sort([axis, kind, order]) Sort an array in-place. split([sep, maxsplit]) For each element in self, return a list of the words in the string, using sep as the delimiter string. splitlines([keepends]) For each element in self, return a list of the lines in the element, breaking at line boundaries. squeeze([axis]) Remove axes of length one from a. startswith(prefix[, start, end]) Returns a boolean array which is True where the string element in self starts with prefix, otherwise False. strip([chars]) For each element in self, return a copy with the leading and trailing characters removed. swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged. swapcase() For each element in self, return a copy of the string with uppercase characters converted to lowercase and vice versa. take(indices[, axis, out, mode]) Return an array formed from the elements of a at the given indices. title() For each element in self, return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase. tofile(fid[, sep, format]) Write array to a file as text or binary (default). tolist() Return the array as an a.ndim-levels deep nested list of Python scalars. tostring([order]) A compatibility alias for tobytes, with exactly the same behavior. translate(table[, deletechars]) For each element in self, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table. transpose(*axes) Returns a view of the array with axes transposed. upper() Return an array with the elements of self converted to uppercase. view([dtype][, type]) New view of array with the same data. zfill(width) Return the numeric string left-filled with zeros in a string of length width.
numpy.reference.generated.numpy.char.chararray
numpy.chararray class numpy.chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order=None)[source] Provides a convenient view on arrays of string and unicode values. Note The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations. Versus a regular NumPy array of type str or unicode, this class adds the following functionality: values automatically have whitespace removed from the end when indexed comparison operators automatically remove whitespace from the end when comparing values vectorized string operations are provided as methods (e.g. endswith) and infix operators (e.g. "+", "*", "%") chararrays should be created using numpy.char.array or numpy.char.asarray, rather than this constructor directly. This constructor creates the array, using buffer (with offset and strides) if it is not None. If buffer is None, then constructs a new array with strides in “C order”, unless both len(shape) >= 2 and order='F', in which case strides is in “Fortran order”. Parameters shapetuple Shape of the array. itemsizeint, optional Length of each array element, in number of characters. Default is 1. unicodebool, optional Are the array elements of type unicode (True) or string (False). Default is False. bufferobject exposing the buffer interface or str, optional Memory address of the start of the array data. Default is None, in which case a new array is created. offsetint, optional Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0. stridesarray_like of ints, optional Strides for the array (see ndarray.strides for full description). Default is None. order{‘C’, ‘F’}, optional The order in which the array data is stored in memory: ‘C’ -> “row major” order (the default), ‘F’ -> “column major” (Fortran) order. Examples >>> charar = np.chararray((3, 3)) >>> charar[:] = 'a' >>> charar chararray([[b'a', b'a', b'a'], [b'a', b'a', b'a'], [b'a', b'a', b'a']], dtype='|S1') >>> charar = np.chararray(charar.shape, itemsize=5) >>> charar[:] = 'abc' >>> charar chararray([[b'abc', b'abc', b'abc'], [b'abc', b'abc', b'abc'], [b'abc', b'abc', b'abc']], dtype='|S5') Attributes T The transposed array. base Base object if memory is from some other object. ctypes An object to simplify the interaction of the array with the ctypes module. data Python buffer object pointing to the start of the array’s data. dtype Data-type of the array’s elements. flags Information about the memory layout of the array. flat A 1-D iterator over the array. imag The imaginary part of the array. itemsize Length of one array element in bytes. nbytes Total bytes consumed by the elements of the array. ndim Number of array dimensions. real The real part of the array. shape Tuple of array dimensions. size Number of elements in the array. strides Tuple of bytes to step in each dimension when traversing an array. Methods astype(dtype[, order, casting, subok, copy]) Copy of the array, cast to a specified type. argsort([axis, kind, order]) Returns the indices that would sort this array. copy([order]) Return a copy of the array. count(sub[, start, end]) Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end]. decode([encoding, errors]) Calls str.decode element-wise. dump(file) Dump a pickle of the array to the specified file. dumps() Returns the pickle of the array as a string. encode([encoding, errors]) Calls str.encode element-wise. endswith(suffix[, start, end]) Returns a boolean array which is True where the string element in self ends with suffix, otherwise False. expandtabs([tabsize]) Return a copy of each string element where all tab characters are replaced by one or more spaces. fill(value) Fill the array with a scalar value. find(sub[, start, end]) For each element, return the lowest index in the string where substring sub is found. flatten([order]) Return a copy of the array collapsed into one dimension. getfield(dtype[, offset]) Returns a field of the given array as a certain type. index(sub[, start, end]) Like find, but raises ValueError when the substring is not found. isalnum() Returns true for each element if all characters in the string are alphanumeric and there is at least one character, false otherwise. isalpha() Returns true for each element if all characters in the string are alphabetic and there is at least one character, false otherwise. isdecimal() For each element in self, return True if there are only decimal characters in the element. isdigit() Returns true for each element if all characters in the string are digits and there is at least one character, false otherwise. islower() Returns true for each element if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. isnumeric() For each element in self, return True if there are only numeric characters in the element. isspace() Returns true for each element if there are only whitespace characters in the string and there is at least one character, false otherwise. istitle() Returns true for each element if the element is a titlecased string and there is at least one character, false otherwise. isupper() Returns true for each element if all cased characters in the string are uppercase and there is at least one character, false otherwise. item(*args) Copy an element of an array to a standard Python scalar and return it. join(seq) Return a string which is the concatenation of the strings in the sequence seq. ljust(width[, fillchar]) Return an array with the elements of self left-justified in a string of length width. lower() Return an array with the elements of self converted to lowercase. lstrip([chars]) For each element in self, return a copy with the leading characters removed. nonzero() Return the indices of the elements that are non-zero. put(indices, values[, mode]) Set a.flat[n] = values[n] for all n in indices. ravel([order]) Return a flattened array. repeat(repeats[, axis]) Repeat elements of an array. replace(old, new[, count]) For each element in self, return a copy of the string with all occurrences of substring old replaced by new. reshape(shape[, order]) Returns an array containing the same data with a new shape. resize(new_shape[, refcheck]) Change shape and size of array in-place. rfind(sub[, start, end]) For each element in self, return the highest index in the string where substring sub is found, such that sub is contained within [start, end]. rindex(sub[, start, end]) Like rfind, but raises ValueError when the substring sub is not found. rjust(width[, fillchar]) Return an array with the elements of self right-justified in a string of length width. rsplit([sep, maxsplit]) For each element in self, return a list of the words in the string, using sep as the delimiter string. rstrip([chars]) For each element in self, return a copy with the trailing characters removed. searchsorted(v[, side, sorter]) Find indices where elements of v should be inserted in a to maintain order. setfield(val, dtype[, offset]) Put a value into a specified place in a field defined by a data-type. setflags([write, align, uic]) Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. sort([axis, kind, order]) Sort an array in-place. split([sep, maxsplit]) For each element in self, return a list of the words in the string, using sep as the delimiter string. splitlines([keepends]) For each element in self, return a list of the lines in the element, breaking at line boundaries. squeeze([axis]) Remove axes of length one from a. startswith(prefix[, start, end]) Returns a boolean array which is True where the string element in self starts with prefix, otherwise False. strip([chars]) For each element in self, return a copy with the leading and trailing characters removed. swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged. swapcase() For each element in self, return a copy of the string with uppercase characters converted to lowercase and vice versa. take(indices[, axis, out, mode]) Return an array formed from the elements of a at the given indices. title() For each element in self, return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase. tofile(fid[, sep, format]) Write array to a file as text or binary (default). tolist() Return the array as an a.ndim-levels deep nested list of Python scalars. tostring([order]) A compatibility alias for tobytes, with exactly the same behavior. translate(table[, deletechars]) For each element in self, return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table. transpose(*axes) Returns a view of the array with axes transposed. upper() Return an array with the elements of self converted to uppercase. view([dtype][, type]) New view of array with the same data. zfill(width) Return the numeric string left-filled with zeros in a string of length width.
numpy.reference.generated.numpy.chararray
numpy.choose numpy.choose(a, choices, out=None, mode='raise')[source] Construct an array from an index array and a list of arrays to choose from. First of all, if confused or uncertain, definitely look at the Examples - in its full generality, this function is less simple than it might seem from the following code description (below ndi = numpy.lib.index_tricks): np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)]). But this omits some subtleties. Here is a fully general summary: Given an “index” array (a) of integers and a sequence of n arrays (choices), a and each choice array are first broadcast, as necessary, to arrays of a common shape; calling these Ba and Bchoices[i], i = 0,…,n-1 we have that, necessarily, Ba.shape == Bchoices[i].shape for each i. Then, a new array with shape Ba.shape is created as follows: if mode='raise' (the default), then, first of all, each element of a (and thus Ba) must be in the range [0, n-1]; now, suppose that i (in that range) is the value at the (j0, j1, ..., jm) position in Ba - then the value at the same position in the new array is the value in Bchoices[i] at that same position; if mode='wrap', values in a (and thus Ba) may be any (signed) integer; modular arithmetic is used to map integers outside the range [0, n-1] back into that range; and then the new array is constructed as above; if mode='clip', values in a (and thus Ba) may be any (signed) integer; negative integers are mapped to 0; values greater than n-1 are mapped to n-1; and then the new array is constructed as above. Parameters aint array This array must contain integers in [0, n-1], where n is the number of choices, unless mode=wrap or mode=clip, in which cases any integers are permissible. choicessequence of arrays Choice arrays. a and all of the choices must be broadcastable to the same shape. If choices is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”. outarray, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype. Note that out is always buffered if mode='raise'; use other modes for better performance. mode{‘raise’ (default), ‘wrap’, ‘clip’}, optional Specifies how indices outside [0, n-1] will be treated: ‘raise’ : an exception is raised ‘wrap’ : value becomes value mod n ‘clip’ : values < 0 are mapped to 0, values > n-1 are mapped to n-1 Returns merged_arrayarray The merged result. Raises ValueError: shape mismatch If a and each choice array are not all broadcastable to the same shape. See also ndarray.choose equivalent method numpy.take_along_axis Preferable if choices is an array Notes To reduce the chance of misinterpretation, even though the following “abuse” is nominally supported, choices should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be either a list or a tuple. Examples >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], ... [20, 21, 22, 23], [30, 31, 32, 33]] >>> np.choose([2, 3, 1, 0], choices ... # the first element of the result will be the first element of the ... # third (2+1) "array" in choices, namely, 20; the second element ... # will be the second element of the fourth (3+1) choice array, i.e., ... # 31, etc. ... ) array([20, 31, 12, 3]) >>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1) array([20, 31, 12, 3]) >>> # because there are 4 choice arrays >>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4) array([20, 1, 12, 3]) >>> # i.e., 0 A couple examples illustrating how choose broadcasts: >>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]] >>> choices = [-10, 10] >>> np.choose(a, choices) array([[ 10, -10, 10], [-10, 10, -10], [ 10, -10, 10]]) >>> # With thanks to Anne Archibald >>> a = np.array([0, 1]).reshape((2,1,1)) >>> c1 = np.array([1, 2, 3]).reshape((1,3,1)) >>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5)) >>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2 array([[[ 1, 1, 1, 1, 1], [ 2, 2, 2, 2, 2], [ 3, 3, 3, 3, 3]], [[-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5], [-1, -2, -3, -4, -5]]])
numpy.reference.generated.numpy.choose
numpy.clip numpy.clip(a, a_min, a_max, out=None, **kwargs)[source] 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 aarray_like Array containing elements to clip. a_min, a_maxarray_like or None Minimum and maximum value. If None, clipping is not performed on the corresponding edge. Only one of a_min and a_max may be None. Both are broadcast against a. outndarray, 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. **kwargs For other keyword-only arguments, see the ufunc docs. New in version 1.17.0. Returns clipped_arrayndarray An array with the elements of a, but where values < a_min are replaced with a_min, and those > a_max with a_max. See also Output type determination 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 >>> 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])
numpy.reference.generated.numpy.clip
class numpy.clongdouble[source] Complex number type composed of two extended-precision floating-point numbers. Character code 'G' Alias numpy.clongfloat Alias numpy.longcomplex Alias on this platform (Linux x86_64) numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.
numpy.reference.arrays.scalars#numpy.clongdouble
numpy.clongfloat[source] alias of numpy.clongdouble
numpy.reference.arrays.scalars#numpy.clongfloat
numpy.column_stack numpy.column_stack(tup)[source] Stack 1-D arrays as columns into a 2-D array. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack. 1-D arrays are turned into 2-D columns first. Parameters tupsequence of 1-D or 2-D arrays. Arrays to stack. All of them must have the same first dimension. Returns stacked2-D array The array formed by stacking the given arrays. See also stack, hstack, vstack, concatenate Examples >>> a = np.array((1,2,3)) >>> b = np.array((2,3,4)) >>> np.column_stack((a,b)) array([[1, 2], [2, 3], [3, 4]])
numpy.reference.generated.numpy.column_stack
numpy.common_type numpy.common_type(*arrays)[source] Return a scalar type which is common to the input arrays. The return type will always be an inexact (i.e. floating point) scalar type, even if all the arrays are integer arrays. If one of the inputs is an integer array, the minimum precision type that is returned is a 64-bit floating point dtype. All input arrays except int64 and uint64 can be safely cast to the returned dtype without loss of information. Parameters array1, array2, …ndarrays Input arrays. Returns outdata type code Data type code. See also dtype, mintypecode Examples >>> np.common_type(np.arange(2, dtype=np.float32)) <class 'numpy.float32'> >>> np.common_type(np.arange(2, dtype=np.float32), np.arange(2)) <class 'numpy.float64'> >>> np.common_type(np.arange(4), np.array([45, 6.j]), np.array([45.0])) <class 'numpy.complex128'>
numpy.reference.generated.numpy.common_type
numpy.complex128[source] alias of numpy.cdouble
numpy.reference.arrays.scalars#numpy.complex128
numpy.complex192 numpy.complex256[source] Alias for numpy.clongdouble, named after its size in bits. The existence of these aliases depends on the platform.
numpy.reference.arrays.scalars#numpy.complex192
numpy.complex192 numpy.complex256[source] Alias for numpy.clongdouble, named after its size in bits. The existence of these aliases depends on the platform.
numpy.reference.arrays.scalars#numpy.complex256
numpy.complex64[source] alias of numpy.csingle
numpy.reference.arrays.scalars#numpy.complex64
numpy.complex_[source] alias of numpy.cdouble
numpy.reference.arrays.scalars#numpy.complex_
numpy.compress numpy.compress(condition, a, axis=None, out=None)[source] Return selected slices of an array along given axis. When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. When working on a 1-D array, compress is equivalent to extract. Parameters condition1-D array of bools Array that selects which entries to return. If len(condition) is less than the size of a along the given axis, then output is truncated to the length of the condition array. aarray_like Array from which to extract a part. axisint, optional Axis along which to take slices. If None (default), work on the flattened array. outndarray, optional Output array. Its type is preserved and it must be of the right shape to hold the output. Returns compressed_arrayndarray A copy of a without the slices along axis for which condition is false. See also take, choose, diag, diagonal, select ndarray.compress Equivalent method in ndarray extract Equivalent method when working on 1-D arrays Output type determination Examples >>> a = np.array([[1, 2], [3, 4], [5, 6]]) >>> a array([[1, 2], [3, 4], [5, 6]]) >>> np.compress([0, 1], a, axis=0) array([[3, 4]]) >>> np.compress([False, True, True], a, axis=0) array([[3, 4], [5, 6]]) >>> np.compress([False, True], a, axis=1) array([[2], [4], [6]]) Working on the flattened array does not return slices along an axis but selects elements. >>> np.compress([False, True], a) array([2])
numpy.reference.generated.numpy.compress
numpy.concatenate numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind") Join a sequence of arrays along an existing axis. Parameters a1, a2, …sequence of array_like The arrays must have the same shape, except in the dimension corresponding to axis (the first, by default). axisint, optional The axis along which the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0. outndarray, optional If provided, the destination to place the result. The shape must be correct, matching that of what concatenate would have returned if no out argument were specified. dtypestr or dtype If provided, the destination array will have this dtype. Cannot be provided together with out. New in version 1.20.0. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional Controls what kind of data casting may occur. Defaults to ‘same_kind’. New in version 1.20.0. Returns resndarray The concatenated array. See also ma.concatenate Concatenate function that preserves input masks. array_split Split an array into multiple sub-arrays of equal or near-equal size. split Split array into a list of multiple sub-arrays of equal size. hsplit Split array into multiple sub-arrays horizontally (column wise). vsplit Split array into multiple sub-arrays vertically (row wise). dsplit Split array into multiple sub-arrays along the 3rd axis (depth). stack Stack a sequence of arrays along a new axis. block Assemble arrays from blocks. hstack Stack arrays in sequence horizontally (column wise). vstack Stack arrays in sequence vertically (row wise). dstack Stack arrays in sequence depth wise (along third dimension). column_stack Stack 1-D arrays as columns into a 2-D array. Notes When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected as input, use the ma.concatenate function from the masked array module instead. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> b = np.array([[5, 6]]) >>> np.concatenate((a, b), axis=0) array([[1, 2], [3, 4], [5, 6]]) >>> np.concatenate((a, b.T), axis=1) array([[1, 2, 5], [3, 4, 6]]) >>> np.concatenate((a, b), axis=None) array([1, 2, 3, 4, 5, 6]) This function will not preserve masking of MaskedArray inputs. >>> a = np.ma.arange(3) >>> a[1] = np.ma.masked >>> b = np.arange(2, 5) >>> a masked_array(data=[0, --, 2], mask=[False, True, False], fill_value=999999) >>> b array([2, 3, 4]) >>> np.concatenate([a, b]) masked_array(data=[0, 1, 2, 2, 3, 4], mask=False, fill_value=999999) >>> np.ma.concatenate([a, b]) masked_array(data=[0, --, 2, 2, 3, 4], mask=[False, True, False, False, False, False], fill_value=999999)
numpy.reference.generated.numpy.concatenate
numpy.conj numpy.conj(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'conjugate'> Return the complex conjugate, element-wise. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part. Parameters xarray_like Input value. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar. Notes conj is an alias for conjugate: >>> np.conj is np.conjugate True Examples >>> np.conjugate(1+2j) (1-2j) >>> x = np.eye(2) + 1j * np.eye(2) >>> np.conjugate(x) array([[ 1.-1.j, 0.-0.j], [ 0.-0.j, 1.-1.j]])
numpy.reference.generated.numpy.conj
numpy.conjugate numpy.conjugate(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'conjugate'> Return the complex conjugate, element-wise. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part. Parameters xarray_like Input value. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray The complex conjugate of x, with same dtype as y. This is a scalar if x is a scalar. Notes conj is an alias for conjugate: >>> np.conj is np.conjugate True Examples >>> np.conjugate(1+2j) (1-2j) >>> x = np.eye(2) + 1j * np.eye(2) >>> np.conjugate(x) array([[ 1.-1.j, 0.-0.j], [ 0.-0.j, 1.-1.j]])
numpy.reference.generated.numpy.conjugate
numpy.convolve numpy.convolve(a, v, mode='full')[source] Returns the discrete, linear convolution of two one-dimensional sequences. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If v is longer than a, the arrays are swapped before computation. Parameters a(N,) array_like First one-dimensional input array. v(M,) array_like Second one-dimensional input array. mode{‘full’, ‘valid’, ‘same’}, optional ‘full’: By default, mode is ‘full’. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen. ‘same’: Mode ‘same’ returns output of length max(M, N). Boundary effects are still visible. ‘valid’: Mode ‘valid’ returns output of length max(M, N) - min(M, N) + 1. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect. Returns outndarray Discrete, linear convolution of a and v. See also scipy.signal.fftconvolve Convolve two arrays using the Fast Fourier Transform. scipy.linalg.toeplitz Used to construct the convolution operator. polymul Polynomial multiplication. Same output as convolve, but also accepts poly1d objects as input. Notes The discrete convolution operation is defined as \[(a * v)[n] = \sum_{m = -\infty}^{\infty} a[m] v[n - m]\] It can be shown that a convolution \(x(t) * y(t)\) in time/space is equivalent to the multiplication \(X(f) Y(f)\) in the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since multiplication is more efficient (faster) than convolution, the function scipy.signal.fftconvolve exploits the FFT to calculate the convolution of large data-sets. References 1 Wikipedia, “Convolution”, https://en.wikipedia.org/wiki/Convolution Examples Note how the convolution operator flips the second array before “sliding” the two across one another: >>> np.convolve([1, 2, 3], [0, 1, 0.5]) array([0. , 1. , 2.5, 4. , 1.5]) Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account: >>> np.convolve([1,2,3],[0,1,0.5], 'same') array([1. , 2.5, 4. ]) The two arrays are of the same length, so there is only one position where they completely overlap: >>> np.convolve([1,2,3],[0,1,0.5], 'valid') array([2.5])
numpy.reference.generated.numpy.convolve
numpy.copy numpy.copy(a, order='K', subok=False)[source] Return an array copy of the given object. Parameters aarray_like Input data. order{‘C’, ‘F’, ‘A’, ‘K’}, optional Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and ndarray.copy are very similar, but have different default values for their order= arguments.) subokbool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (defaults to False). New in version 1.19.0. Returns arrndarray Array interpretation of a. See also ndarray.copy Preferred method for creating an array copy Notes This is equivalent to: >>> np.array(a, copy=True) Examples Create an array x, with a reference y and a copy z: >>> x = np.array([1, 2, 3]) >>> y = x >>> z = np.copy(x) Note that, when we modify x, y changes, but not z: >>> x[0] = 10 >>> x[0] == y[0] True >>> x[0] == z[0] False Note that, np.copy clears previously set WRITEABLE=False flag. >>> a = np.array([1, 2, 3]) >>> a.flags["WRITEABLE"] = False >>> b = np.copy(a) >>> b.flags["WRITEABLE"] True >>> b[0] = 3 >>> b array([3, 2, 3]) Note that np.copy is a shallow copy and will not copy object elements within arrays. This is mainly important for arrays containing Python objects. The new array will contain the same object which may lead to surprises if that object can be modified (is mutable): >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object) >>> b = np.copy(a) >>> b[2][0] = 10 >>> a array([1, 'm', list([10, 3, 4])], dtype=object) To ensure all elements within an object array are copied, use copy.deepcopy: >>> import copy >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object) >>> c = copy.deepcopy(a) >>> c[2][0] = 10 >>> c array([1, 'm', list([10, 3, 4])], dtype=object) >>> a array([1, 'm', list([2, 3, 4])], dtype=object)
numpy.reference.generated.numpy.copy
numpy.copysign numpy.copysign(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'copysign'> Change the sign of x1 to that of x2, element-wise. If x2 is a scalar, its sign will be copied to all elements of x1. Parameters x1array_like Values to change the sign of. x2array_like The sign of x2 is copied to x1. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars. Examples >>> np.copysign(1.3, -1) -1.3 >>> 1/np.copysign(0, 1) inf >>> 1/np.copysign(0, -1) -inf >>> np.copysign([-1, 0, 1], -1.1) array([-1., -0., -1.]) >>> np.copysign([-1, 0, 1], np.arange(3)-1) array([-1., 0., 1.])
numpy.reference.generated.numpy.copysign
numpy.copyto numpy.copyto(dst, src, casting='same_kind', where=True) Copies values from one array to another, broadcasting as necessary. Raises a TypeError if the casting rule is violated, and if where is provided, it selects which elements to copy. New in version 1.7.0. Parameters dstndarray The array into which values are copied. srcarray_like The array from which values are copied. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional Controls what kind of data casting may occur when copying. ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done. wherearray_like of bool, optional A boolean array which is broadcasted to match the dimensions of dst, and selects elements to copy from src to dst wherever it contains the value True.
numpy.reference.generated.numpy.copyto
numpy.corrcoef numpy.corrcoef(x, y=None, rowvar=True, bias=<no value>, ddof=<no value>, *, dtype=None)[source] Return Pearson product-moment correlation coefficients. Please refer to the documentation for cov for more detail. The relationship between the correlation coefficient matrix, R, and the covariance matrix, C, is \[R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }\] The values of R are between -1 and 1, inclusive. Parameters xarray_like A 1-D or 2-D array containing multiple variables and observations. Each row of x represents a variable, and each column a single observation of all those variables. Also see rowvar below. yarray_like, optional An additional set of variables and observations. y has the same shape as x. rowvarbool, optional If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. bias_NoValue, optional Has no effect, do not use. Deprecated since version 1.10.0. ddof_NoValue, optional Has no effect, do not use. Deprecated since version 1.10.0. dtypedata-type, optional Data-type of the result. By default, the return data-type will have at least numpy.float64 precision. New in version 1.20. Returns Rndarray The correlation coefficient matrix of the variables. See also cov Covariance matrix Notes Due to floating point rounding the resulting array may not be Hermitian, the diagonal elements may not be 1, and the elements may not satisfy the inequality abs(a) <= 1. The real and imaginary parts are clipped to the interval [-1, 1] in an attempt to improve on that situation but is not much help in the complex case. This function accepts but discards arguments bias and ddof. This is for backwards compatibility with previous versions of this function. These arguments had no effect on the return values of the function and can be safely ignored in this and previous versions of numpy. Examples In this example we generate two random arrays, xarr and yarr, and compute the row-wise and column-wise Pearson correlation coefficients, R. Since rowvar is true by default, we first find the row-wise Pearson correlation coefficients between the variables of xarr. >>> import numpy as np >>> rng = np.random.default_rng(seed=42) >>> xarr = rng.random((3, 3)) >>> xarr array([[0.77395605, 0.43887844, 0.85859792], [0.69736803, 0.09417735, 0.97562235], [0.7611397 , 0.78606431, 0.12811363]]) >>> R1 = np.corrcoef(xarr) >>> R1 array([[ 1. , 0.99256089, -0.68080986], [ 0.99256089, 1. , -0.76492172], [-0.68080986, -0.76492172, 1. ]]) If we add another set of variables and observations yarr, we can compute the row-wise Pearson correlation coefficients between the variables in xarr and yarr. >>> yarr = rng.random((3, 3)) >>> yarr array([[0.45038594, 0.37079802, 0.92676499], [0.64386512, 0.82276161, 0.4434142 ], [0.22723872, 0.55458479, 0.06381726]]) >>> R2 = np.corrcoef(xarr, yarr) >>> R2 array([[ 1. , 0.99256089, -0.68080986, 0.75008178, -0.934284 , -0.99004057], [ 0.99256089, 1. , -0.76492172, 0.82502011, -0.97074098, -0.99981569], [-0.68080986, -0.76492172, 1. , -0.99507202, 0.89721355, 0.77714685], [ 0.75008178, 0.82502011, -0.99507202, 1. , -0.93657855, -0.83571711], [-0.934284 , -0.97074098, 0.89721355, -0.93657855, 1. , 0.97517215], [-0.99004057, -0.99981569, 0.77714685, -0.83571711, 0.97517215, 1. ]]) Finally if we use the option rowvar=False, the columns are now being treated as the variables and we will find the column-wise Pearson correlation coefficients between variables in xarr and yarr. >>> R3 = np.corrcoef(xarr, yarr, rowvar=False) >>> R3 array([[ 1. , 0.77598074, -0.47458546, -0.75078643, -0.9665554 , 0.22423734], [ 0.77598074, 1. , -0.92346708, -0.99923895, -0.58826587, -0.44069024], [-0.47458546, -0.92346708, 1. , 0.93773029, 0.23297648, 0.75137473], [-0.75078643, -0.99923895, 0.93773029, 1. , 0.55627469, 0.47536961], [-0.9665554 , -0.58826587, 0.23297648, 0.55627469, 1. , -0.46666491], [ 0.22423734, -0.44069024, 0.75137473, 0.47536961, -0.46666491, 1. ]])
numpy.reference.generated.numpy.corrcoef
numpy.correlate numpy.correlate(a, v, mode='valid')[source] Cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts: c_{av}[k] = sum_n a[n+k] * conj(v[n]) with a and v sequences being zero-padded where necessary and conj being the conjugate. Parameters a, varray_like Input sequences. mode{‘valid’, ‘same’, ‘full’}, optional Refer to the convolve docstring. Note that the default is ‘valid’, unlike convolve, which uses ‘full’. old_behaviorbool old_behavior was removed in NumPy 1.10. If you need the old behavior, use multiarray.correlate. Returns outndarray Discrete cross-correlation of a and v. See also convolve Discrete, linear convolution of two one-dimensional sequences. multiarray.correlate Old, no conjugate, version of correlate. scipy.signal.correlate uses FFT which has superior performance on large arrays. Notes The definition of correlation above is not unique and sometimes correlation may be defined differently. Another common definition is: c'_{av}[k] = sum_n a[n] conj(v[n+k]) which is related to c_{av}[k] by c'_{av}[k] = c_{av}[-k]. numpy.correlate may perform slowly in large arrays (i.e. n = 1e5) because it does not use the FFT to compute the convolution; in that case, scipy.signal.correlate might be preferable. Examples >>> np.correlate([1, 2, 3], [0, 1, 0.5]) array([3.5]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "same") array([2. , 3.5, 3. ]) >>> np.correlate([1, 2, 3], [0, 1, 0.5], "full") array([0.5, 2. , 3.5, 3. , 0. ]) Using complex sequences: >>> np.correlate([1+1j, 2, 3-1j], [0, 1, 0.5j], 'full') array([ 0.5-0.5j, 1.0+0.j , 1.5-1.5j, 3.0-1.j , 0.0+0.j ]) Note that you get the time reversed, complex conjugated result when the two input sequences change places, i.e., c_{va}[k] = c^{*}_{av}[-k]: >>> np.correlate([0, 1, 0.5j], [1+1j, 2, 3-1j], 'full') array([ 0.0+0.j , 3.0+1.j , 1.5+1.5j, 1.0+0.j , 0.5+0.5j])
numpy.reference.generated.numpy.correlate
numpy.cos numpy.cos(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'cos'> Cosine element-wise. Parameters xarray_like Input array in radians. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray The corresponding cosine values. This is a scalar if x is a scalar. Notes If out is provided, the function writes the result into it, and returns a reference to out. (See Examples) References M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972. Examples >>> np.cos(np.array([0, np.pi/2, np.pi])) array([ 1.00000000e+00, 6.12303177e-17, -1.00000000e+00]) >>> >>> # Example of providing the optional output parameter >>> out1 = np.array([0], dtype='d') >>> out2 = np.cos([0.1], out1) >>> out2 is out1 True >>> >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.cos(np.zeros((3,3)),np.zeros((2,2))) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operands could not be broadcast together with shapes (3,3) (2,2)
numpy.reference.generated.numpy.cos
numpy.cosh numpy.cosh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'cosh'> Hyperbolic cosine, element-wise. Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j*x). Parameters xarray_like Input array. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Output array of same shape as x. This is a scalar if x is a scalar. Examples >>> np.cosh(0) 1.0 The hyperbolic cosine describes the shape of a hanging cable: >>> import matplotlib.pyplot as plt >>> x = np.linspace(-4, 4, 1000) >>> plt.plot(x, np.cosh(x)) >>> plt.show()
numpy.reference.generated.numpy.cosh
numpy.count_nonzero numpy.count_nonzero(a, axis=None, *, keepdims=False)[source] Counts the number of non-zero values in the array a. The word “non-zero” is in reference to the Python 2.x built-in method __nonzero__() (renamed __bool__() in Python 3.x) of Python objects that tests an object’s “truthfulness”. For example, any number is considered truthful if it is nonzero, whereas any string is considered truthful if it is not the empty string. Thus, this function (recursively) counts how many elements in a (and in sub-arrays thereof) have their __nonzero__() or __bool__() method evaluated to True. Parameters aarray_like The array for which to count non-zeros. axisint or tuple, optional Axis or tuple of axes along which to count non-zeros. Default is None, meaning that non-zeros will be counted along a flattened version of a. New in version 1.12.0. keepdimsbool, optional If this is set to True, the axes that are counted are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. New in version 1.19.0. Returns countint or array of int Number of non-zero values in the array along a given axis. Otherwise, the total number of non-zero values in the array is returned. See also nonzero Return the coordinates of all the non-zero values. Examples >>> np.count_nonzero(np.eye(4)) 4 >>> a = np.array([[0, 1, 7, 0], ... [3, 0, 2, 19]]) >>> np.count_nonzero(a) 5 >>> np.count_nonzero(a, axis=0) array([1, 1, 2, 1]) >>> np.count_nonzero(a, axis=1) array([2, 3]) >>> np.count_nonzero(a, axis=1, keepdims=True) array([[2], [3]])
numpy.reference.generated.numpy.count_nonzero
numpy.cov numpy.cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None)[source] Estimate a covariance matrix, given data and weights. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, \(X = [x_1, x_2, ... x_N]^T\), then the covariance matrix element \(C_{ij}\) is the covariance of \(x_i\) and \(x_j\). The element \(C_{ii}\) is the variance of \(x_i\). See the notes for an outline of the algorithm. Parameters marray_like A 1-D or 2-D array containing multiple variables and observations. Each row of m represents a variable, and each column a single observation of all those variables. Also see rowvar below. yarray_like, optional An additional set of variables and observations. y has the same form as that of m. rowvarbool, optional If rowvar is True (default), then each row represents a variable, with observations in the columns. Otherwise, the relationship is transposed: each column represents a variable, while the rows contain observations. biasbool, optional Default normalization (False) is by (N - 1), where N is the number of observations given (unbiased estimate). If bias is True, then normalization is by N. These values can be overridden by using the keyword ddof in numpy versions >= 1.5. ddofint, optional If not None the default value implied by bias is overridden. Note that ddof=1 will return the unbiased estimate, even if both fweights and aweights are specified, and ddof=0 will return the simple average. See the notes for the details. The default value is None. New in version 1.5. fweightsarray_like, int, optional 1-D array of integer frequency weights; the number of times each observation vector should be repeated. New in version 1.10. aweightsarray_like, optional 1-D array of observation vector weights. These relative weights are typically large for observations considered “important” and smaller for observations considered less “important”. If ddof=0 the array of weights can be used to assign probabilities to observation vectors. New in version 1.10. dtypedata-type, optional Data-type of the result. By default, the return data-type will have at least numpy.float64 precision. New in version 1.20. Returns outndarray The covariance matrix of the variables. See also corrcoef Normalized covariance matrix Notes Assume that the observations are in the columns of the observation array m and let f = fweights and a = aweights for brevity. The steps to compute the weighted covariance are as follows: >>> m = np.arange(10, dtype=np.float64) >>> f = np.arange(10) * 2 >>> a = np.arange(10) ** 2. >>> ddof = 1 >>> w = f * a >>> v1 = np.sum(w) >>> v2 = np.sum(w * a) >>> m -= np.sum(m * w, axis=None, keepdims=True) / v1 >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2) Note that when a == 1, the normalization factor v1 / (v1**2 - ddof * v2) goes over to 1 / (np.sum(f) - ddof) as it should. Examples Consider two variables, \(x_0\) and \(x_1\), which correlate perfectly, but in opposite directions: >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T >>> x array([[0, 1, 2], [2, 1, 0]]) Note how \(x_0\) increases while \(x_1\) decreases. The covariance matrix shows this clearly: >>> np.cov(x) array([[ 1., -1.], [-1., 1.]]) Note that element \(C_{0,1}\), which shows the correlation between \(x_0\) and \(x_1\), is negative. Further, note how x and y are combined: >>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.stack((x, y), axis=0) >>> np.cov(X) array([[11.71 , -4.286 ], # may vary [-4.286 , 2.144133]]) >>> np.cov(x, y) array([[11.71 , -4.286 ], # may vary [-4.286 , 2.144133]]) >>> np.cov(x) array(11.71)
numpy.reference.generated.numpy.cov
numpy.cross numpy.cross(a, b, axisa=- 1, axisb=- 1, axisc=- 1, axis=None)[source] Return the cross product of two (arrays of) vectors. The cross product of a and b in \(R^3\) is a vector perpendicular to both a and b. If a and b are arrays of vectors, the vectors are defined by the last axis of a and b by default, and these axes can have dimensions 2 or 3. Where the dimension of either a or b is 2, the third component of the input vector is assumed to be zero and the cross product calculated accordingly. In cases where both input vectors have dimension 2, the z-component of the cross product is returned. Parameters aarray_like Components of the first vector(s). barray_like Components of the second vector(s). axisaint, optional Axis of a that defines the vector(s). By default, the last axis. axisbint, optional Axis of b that defines the vector(s). By default, the last axis. axiscint, optional Axis of c containing the cross product vector(s). Ignored if both input vectors have dimension 2, as the return is scalar. By default, the last axis. axisint, optional If defined, the axis of a, b and c that defines the vector(s) and cross product(s). Overrides axisa, axisb and axisc. Returns cndarray Vector cross product(s). Raises ValueError When the dimension of the vector(s) in a and/or b does not equal 2 or 3. See also inner Inner product outer Outer product. ix_ Construct index arrays. Notes New in version 1.9.0. Supports full broadcasting of the inputs. Examples Vector cross-product. >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> np.cross(x, y) array([-3, 6, -3]) One vector with dimension 2. >>> x = [1, 2] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3]) Equivalently: >>> x = [1, 2, 0] >>> y = [4, 5, 6] >>> np.cross(x, y) array([12, -6, -3]) Both vectors with dimension 2. >>> x = [1,2] >>> y = [4,5] >>> np.cross(x, y) array(-3) Multiple vector cross-products. Note that the direction of the cross product vector is defined by the right-hand rule. >>> x = np.array([[1,2,3], [4,5,6]]) >>> y = np.array([[4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[-3, 6, -3], [ 3, -6, 3]]) The orientation of c can be changed using the axisc keyword. >>> np.cross(x, y, axisc=0) array([[-3, 3], [ 6, -6], [-3, 3]]) Change the vector definition of x and y using axisa and axisb. >>> x = np.array([[1,2,3], [4,5,6], [7, 8, 9]]) >>> y = np.array([[7, 8, 9], [4,5,6], [1,2,3]]) >>> np.cross(x, y) array([[ -6, 12, -6], [ 0, 0, 0], [ 6, -12, 6]]) >>> np.cross(x, y, axisa=0, axisb=0) array([[-24, 48, -24], [-30, 60, -30], [-36, 72, -36]])
numpy.reference.generated.numpy.cross
class numpy.csingle[source] Complex number type composed of two single-precision floating-point numbers. Character code 'F' Alias numpy.singlecomplex Alias on this platform (Linux x86_64) numpy.complex64: Complex number type composed of 2 32-bit-precision floating-point numbers.
numpy.reference.arrays.scalars#numpy.csingle
C-Types Foreign Function Interface (numpy.ctypeslib) numpy.ctypeslib.as_array(obj, shape=None)[source] Create a numpy array from a ctypes array or POINTER. The numpy array shares the memory with the ctypes object. The shape parameter must be given if converting from a ctypes POINTER. The shape parameter is ignored if converting from a ctypes array numpy.ctypeslib.as_ctypes(obj)[source] Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted. numpy.ctypeslib.as_ctypes_type(dtype)[source] Convert a dtype into a ctypes type. Parameters dtypedtype The dtype to convert Returns ctype A ctype scalar, union, array, or struct Raises NotImplementedError If the conversion is not possible Notes This function does not losslessly round-trip in either direction. np.dtype(as_ctypes_type(dt)) will: insert padding fields reorder fields to be sorted by offset discard field titles as_ctypes_type(np.dtype(ctype)) will: discard the class names of ctypes.Structures and ctypes.Unions convert single-element ctypes.Unions into single-element ctypes.Structures insert padding fields numpy.ctypeslib.load_library(libname, loader_path)[source] It is possible to load a library using >>> lib = ctypes.cdll[<full_path_name>] But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. NumPy supplies the load_library function as a convenience. Changed in version 1.20.0: Allow libname and loader_path to take any path-like object. Parameters libnamepath-like Name of the library, which can have ‘lib’ as a prefix, but without an extension. loader_pathpath-like Where the library can be found. Returns ctypes.cdll[libpath]library object A ctypes library object Raises OSError If there is no library with the expected extension, or the library is defective and cannot be loaded. numpy.ctypeslib.ndpointer(dtype=None, ndim=None, shape=None, flags=None)[source] Array-checking restype/argtypes. An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, POINTER(c_double), since several restrictions can be specified, which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and flags. If a given array does not satisfy the specified restrictions, a TypeError is raised. Parameters dtypedata-type, optional Array data-type. ndimint, optional Number of array dimensions. shapetuple of ints, optional Array shape. flagsstr or tuple of str Array flags; may be one or more of: C_CONTIGUOUS / C / CONTIGUOUS F_CONTIGUOUS / F / FORTRAN OWNDATA / O WRITEABLE / W ALIGNED / A WRITEBACKIFCOPY / X UPDATEIFCOPY / U Returns klassndpointer type object A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags information. Raises TypeError If a given array does not satisfy the specified restrictions. Examples >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ... ndim=1, ... flags='C_CONTIGUOUS')] ... >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) ... class numpy.ctypeslib.c_intp A ctypes signed integer type of the same size as numpy.intp. Depending on the platform, it can be an alias for either c_int, c_long or c_longlong.
numpy.reference.routines.ctypeslib
numpy.ctypeslib.as_ctypes(obj)[source] Create and return a ctypes object from a numpy array. Actually anything that exposes the __array_interface__ is accepted.
numpy.reference.routines.ctypeslib#numpy.ctypeslib.as_ctypes
numpy.ctypeslib.as_ctypes_type(dtype)[source] Convert a dtype into a ctypes type. Parameters dtypedtype The dtype to convert Returns ctype A ctype scalar, union, array, or struct Raises NotImplementedError If the conversion is not possible Notes This function does not losslessly round-trip in either direction. np.dtype(as_ctypes_type(dt)) will: insert padding fields reorder fields to be sorted by offset discard field titles as_ctypes_type(np.dtype(ctype)) will: discard the class names of ctypes.Structures and ctypes.Unions convert single-element ctypes.Unions into single-element ctypes.Structures insert padding fields
numpy.reference.routines.ctypeslib#numpy.ctypeslib.as_ctypes_type
class numpy.ctypeslib.c_intp A ctypes signed integer type of the same size as numpy.intp. Depending on the platform, it can be an alias for either c_int, c_long or c_longlong.
numpy.reference.routines.ctypeslib#numpy.ctypeslib.c_intp
numpy.ctypeslib.load_library(libname, loader_path)[source] It is possible to load a library using >>> lib = ctypes.cdll[<full_path_name>] But there are cross-platform considerations, such as library file extensions, plus the fact Windows will just load the first library it finds with that name. NumPy supplies the load_library function as a convenience. Changed in version 1.20.0: Allow libname and loader_path to take any path-like object. Parameters libnamepath-like Name of the library, which can have ‘lib’ as a prefix, but without an extension. loader_pathpath-like Where the library can be found. Returns ctypes.cdll[libpath]library object A ctypes library object Raises OSError If there is no library with the expected extension, or the library is defective and cannot be loaded.
numpy.reference.routines.ctypeslib#numpy.ctypeslib.load_library
numpy.ctypeslib.ndpointer(dtype=None, ndim=None, shape=None, flags=None)[source] Array-checking restype/argtypes. An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach is more flexible than using, for example, POINTER(c_double), since several restrictions can be specified, which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and flags. If a given array does not satisfy the specified restrictions, a TypeError is raised. Parameters dtypedata-type, optional Array data-type. ndimint, optional Number of array dimensions. shapetuple of ints, optional Array shape. flagsstr or tuple of str Array flags; may be one or more of: C_CONTIGUOUS / C / CONTIGUOUS F_CONTIGUOUS / F / FORTRAN OWNDATA / O WRITEABLE / W ALIGNED / A WRITEBACKIFCOPY / X UPDATEIFCOPY / U Returns klassndpointer type object A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags information. Raises TypeError If a given array does not satisfy the specified restrictions. Examples >>> clib.somefunc.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64, ... ndim=1, ... flags='C_CONTIGUOUS')] ... >>> clib.somefunc(np.array([1, 2, 3], dtype=np.float64)) ...
numpy.reference.routines.ctypeslib#numpy.ctypeslib.ndpointer
numpy.cumprod numpy.cumprod(a, axis=None, dtype=None, out=None)[source] Return the cumulative product of elements along a given axis. Parameters aarray_like Input array. axisint, optional Axis along which the cumulative product is computed. By default the input is flattened. dtypedtype, optional Type of the returned array, as well as of the accumulator in which the elements are multiplied. 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 instead. outndarray, 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 of the resulting values will be cast if necessary. Returns cumprodndarray A new array holding the result is returned unless out is specified, in which case a reference to out is returned. See also Output type determination Notes Arithmetic is modular when using integer types, and no error is raised on overflow. Examples >>> a = np.array([1,2,3]) >>> np.cumprod(a) # intermediate results 1, 1*2 ... # total product 1*2*3 = 6 array([1, 2, 6]) >>> a = np.array([[1, 2, 3], [4, 5, 6]]) >>> np.cumprod(a, dtype=float) # specify type of output array([ 1., 2., 6., 24., 120., 720.]) The cumulative product for each column (i.e., over the rows) of a: >>> np.cumprod(a, axis=0) array([[ 1, 2, 3], [ 4, 10, 18]]) The cumulative product for each row (i.e. over the columns) of a: >>> np.cumprod(a,axis=1) array([[ 1, 2, 6], [ 4, 20, 120]])
numpy.reference.generated.numpy.cumprod
numpy.cumsum numpy.cumsum(a, axis=None, dtype=None, out=None)[source] Return the cumulative sum of the elements along a given axis. Parameters aarray_like Input array. axisint, optional Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. dtypedtype, 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. outndarray, 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_axisndarray. 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. See also sum Sum array elements. trapz Integration of array values using the composite trapezoidal rule. diff Calculate 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 to sum(a) for floating-point values since sum may use a pairwise summation routine, reducing the roundoff-error. See sum for more information. Examples >>> 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=float) # 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 to sum(b) >>> b = np.array([1, 2e-9, 3e-9] * 1000000) >>> b.cumsum()[-1] 1000000.0050045159 >>> b.sum() 1000000.0050000029
numpy.reference.generated.numpy.cumsum
numpy.DataSource class numpy.DataSource(destpath='.')[source] A generic data source file (file, http, ftp, …). DataSources can be local files or remote files/URLs. The files may also be compressed or uncompressed. DataSource hides some of the low-level details of downloading the file, allowing you to simply pass in a valid file path (or URL) and obtain a file object. Parameters destpathstr or None, optional Path to the directory where the source file gets downloaded to for use. If destpath is None, a temporary directory will be created. The default path is the current directory. Notes URLs require a scheme string (http://) to be used, without it they will fail: >>> repos = np.DataSource() >>> repos.exists('www.google.com/index.html') False >>> repos.exists('http://www.google.com/index.html') True Temporary directories are deleted when the DataSource is deleted. Examples >>> ds = np.DataSource('/home/guido') >>> urlname = 'http://www.google.com/' >>> gfile = ds.open('http://www.google.com/') >>> ds.abspath(urlname) '/home/guido/www.google.com/index.html' >>> ds = np.DataSource(None) # use with temporary file >>> ds.open('/home/guido/foobar.txt') <open file '/home/guido.foobar.txt', mode 'r' at 0x91d4430> >>> ds.abspath('/home/guido/foobar.txt') '/tmp/.../home/guido/foobar.txt' Methods abspath(path) Return absolute path of file in the DataSource directory. exists(path) Test if path exists. open(path[, mode, encoding, newline]) Open and return file-like object.
numpy.reference.generated.numpy.datasource
class numpy.datetime64[source] If created from a 64-bit integer, it represents an offset from 1970-01-01T00:00:00. If created from string, the string can be in ISO 8601 date or datetime format. >>> np.datetime64(10, 'Y') numpy.datetime64('1980') >>> np.datetime64('1980', 'Y') numpy.datetime64('1980') >>> np.datetime64(10, 'D') numpy.datetime64('1970-01-11') See Datetimes and Timedeltas for more information. Character code 'M'
numpy.reference.arrays.scalars#numpy.datetime64
numpy.datetime_as_string numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind') Convert an array of datetimes into an array of strings. Parameters arrarray_like of datetime64 The array of UTC timestamps to format. unitstr One of None, ‘auto’, or a datetime unit. timezone{‘naive’, ‘UTC’, ‘local’} or tzinfo Timezone information to use when displaying the datetime. If ‘UTC’, end with a Z to indicate UTC time. If ‘local’, convert to the local timezone first, and suffix with a +-#### timezone offset. If a tzinfo object, then do as with ‘local’, but use the specified timezone. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’} Casting to allow when changing between datetime units. Returns str_arrndarray An array of strings the same shape as arr. Examples >>> import pytz >>> d = np.arange('2002-10-27T04:30', 4*60, 60, dtype='M8[m]') >>> d array(['2002-10-27T04:30', '2002-10-27T05:30', '2002-10-27T06:30', '2002-10-27T07:30'], dtype='datetime64[m]') Setting the timezone to UTC shows the same information, but with a Z suffix >>> np.datetime_as_string(d, timezone='UTC') array(['2002-10-27T04:30Z', '2002-10-27T05:30Z', '2002-10-27T06:30Z', '2002-10-27T07:30Z'], dtype='<U35') Note that we picked datetimes that cross a DST boundary. Passing in a pytz timezone object will print the appropriate offset >>> np.datetime_as_string(d, timezone=pytz.timezone('US/Eastern')) array(['2002-10-27T00:30-0400', '2002-10-27T01:30-0400', '2002-10-27T01:30-0500', '2002-10-27T02:30-0500'], dtype='<U39') Passing in a unit will change the precision >>> np.datetime_as_string(d, unit='h') array(['2002-10-27T04', '2002-10-27T05', '2002-10-27T06', '2002-10-27T07'], dtype='<U32') >>> np.datetime_as_string(d, unit='s') array(['2002-10-27T04:30:00', '2002-10-27T05:30:00', '2002-10-27T06:30:00', '2002-10-27T07:30:00'], dtype='<U38') ‘casting’ can be used to specify whether precision can be changed >>> np.datetime_as_string(d, unit='h', casting='safe') Traceback (most recent call last): ... TypeError: Cannot create a datetime string as units 'h' from a NumPy datetime with units 'm' according to the rule 'safe'
numpy.reference.generated.numpy.datetime_as_string
numpy.datetime_data numpy.datetime_data(dtype, /) Get information about the step size of a date or time type. The returned tuple can be passed as the second argument of numpy.datetime64 and numpy.timedelta64. Parameters dtypedtype The dtype object, which must be a datetime64 or timedelta64 type. Returns unitstr The datetime unit on which this dtype is based. countint The number of base units in a step. Examples >>> dt_25s = np.dtype('timedelta64[25s]') >>> np.datetime_data(dt_25s) ('s', 25) >>> np.array(10, dt_25s).astype('timedelta64[s]') array(250, dtype='timedelta64[s]') The result can be used to construct a datetime that uses the same units as a timedelta >>> np.datetime64('2010', np.datetime_data(dt_25s)) numpy.datetime64('2010-01-01T00:00:00','25s')
numpy.reference.generated.numpy.datetime_data
numpy.deg2rad numpy.deg2rad(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'deg2rad'> Convert angles from degrees to radians. Parameters xarray_like Angles in degrees. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray The corresponding angle in radians. This is a scalar if x is a scalar. See also rad2deg Convert angles from radians to degrees. unwrap Remove large jumps in angle by wrapping. Notes New in version 1.3.0. deg2rad(x) is x * pi / 180. Examples >>> np.deg2rad(180) 3.1415926535897931
numpy.reference.generated.numpy.deg2rad
numpy.degrees numpy.degrees(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'degrees'> Convert angles from radians to degrees. Parameters xarray_like Input array in radians. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray of floats The corresponding degree values; if out was supplied this is a reference to it. This is a scalar if x is a scalar. See also rad2deg equivalent function Examples Convert a radian array to degrees >>> rad = np.arange(12.)*np.pi/6 >>> np.degrees(rad) array([ 0., 30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330.]) >>> out = np.zeros((rad.shape)) >>> r = np.degrees(rad, out) >>> np.all(r == out) True
numpy.reference.generated.numpy.degrees
numpy.delete numpy.delete(arr, obj, axis=None)[source] Return a new array with sub-arrays along an axis deleted. For a one dimensional array, this returns those entries not returned by arr[obj]. Parameters arrarray_like Input array. objslice, int or array of ints Indicate indices of sub-arrays to remove along the specified axis. Changed in version 1.19.0: Boolean indices are now treated as a mask of elements to remove, rather than being cast to the integers 0 and 1. axisint, optional The axis along which to delete the subarray defined by obj. If axis is None, obj is applied to the flattened array. Returns outndarray A copy of arr with the elements specified by obj removed. Note that delete does not occur in-place. If axis is None, out is a flattened array. See also insert Insert elements into an array. append Append elements at the end of an array. Notes Often it is preferable to use a boolean mask. For example: >>> arr = np.arange(12) + 1 >>> mask = np.ones(len(arr), dtype=bool) >>> mask[[0,2,4]] = False >>> result = arr[mask,...] Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further use of mask. Examples >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) >>> arr array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]]) >>> np.delete(arr, 1, 0) array([[ 1, 2, 3, 4], [ 9, 10, 11, 12]]) >>> np.delete(arr, np.s_[::2], 1) array([[ 2, 4], [ 6, 8], [10, 12]]) >>> np.delete(arr, [1,3,5], None) array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])
numpy.reference.generated.numpy.delete
numpy.deprecate numpy.deprecate(*args, **kwargs)[source] Issues a DeprecationWarning, adds warning to old_name’s docstring, rebinds old_name.__name__ and returns the new function object. This function may also be used as a decorator. Parameters funcfunction The function to be deprecated. old_namestr, optional The name of the function to be deprecated. Default is None, in which case the name of func is used. new_namestr, optional The new name for the function. Default is None, in which case the deprecation message is that old_name is deprecated. If given, the deprecation message is that old_name is deprecated and new_name should be used instead. messagestr, optional Additional explanation of the deprecation. Displayed in the docstring after the warning. Returns old_funcfunction The deprecated function. Examples Note that olduint returns a value after printing Deprecation Warning: >>> olduint = np.deprecate(np.uint) DeprecationWarning: `uint64` is deprecated! # may vary >>> olduint(6) 6
numpy.reference.generated.numpy.deprecate
numpy.deprecate_with_doc numpy.deprecate_with_doc(msg)[source] Deprecates a function and includes the deprecation in its docstring. This function is used as a decorator. It returns an object that can be used to issue a DeprecationWarning, by passing the to-be decorated function as argument, this adds warning to the to-be decorated function’s docstring and returns the new function object. Parameters msgstr Additional explanation of the deprecation. Displayed in the docstring after the warning. Returns objobject See also deprecate Decorate a function such that it issues a DeprecationWarning
numpy.reference.generated.numpy.deprecate_with_doc
numpy.diag numpy.diag(v, k=0)[source] Extract a diagonal or construct a diagonal array. See the more detailed documentation for numpy.diagonal if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using. Parameters varray_like If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array with v on the k-th diagonal. kint, optional Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal. Returns outndarray The extracted diagonal or constructed diagonal array. See also diagonal Return specified diagonals. diagflat Create a 2-D array with the flattened input as a diagonal. trace Sum along diagonals. triu Upper triangle of an array. tril Lower triangle of an array. Examples >>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.diag(x) array([0, 4, 8]) >>> np.diag(x, k=1) array([1, 5]) >>> np.diag(x, k=-1) array([3, 7]) >>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]])
numpy.reference.generated.numpy.diag
numpy.diag_indices numpy.diag_indices(n, ndim=2)[source] Return the indices to access the main diagonal of an array. This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2 dimensions and shape (n, n, …, n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is the set of indices to access a[i, i, ..., i] for i = [0..n-1]. Parameters nint The size, along each dimension, of the arrays for which the returned indices can be used. ndimint, optional The number of dimensions. See also diag_indices_from Notes New in version 1.4.0. Examples Create a set of indices to access the diagonal of a (4, 4) array: >>> di = np.diag_indices(4) >>> di (array([0, 1, 2, 3]), array([0, 1, 2, 3])) >>> a = np.arange(16).reshape(4, 4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> a[di] = 100 >>> a array([[100, 1, 2, 3], [ 4, 100, 6, 7], [ 8, 9, 100, 11], [ 12, 13, 14, 100]]) Now, we create indices to manipulate a 3-D array: >>> d3 = np.diag_indices(2, 3) >>> d3 (array([0, 1]), array([0, 1]), array([0, 1])) And use it to set the diagonal of an array of zeros to 1: >>> a = np.zeros((2, 2, 2), dtype=int) >>> a[d3] = 1 >>> a array([[[1, 0], [0, 0]], [[0, 0], [0, 1]]])
numpy.reference.generated.numpy.diag_indices
numpy.diag_indices_from numpy.diag_indices_from(arr)[source] Return the indices to access the main diagonal of an n-dimensional array. See diag_indices for full details. Parameters arrarray, at least 2-D See also diag_indices Notes New in version 1.4.0.
numpy.reference.generated.numpy.diag_indices_from
numpy.diagflat numpy.diagflat(v, k=0)[source] Create a two-dimensional array with the flattened input as a diagonal. Parameters varray_like Input data, which is flattened and set as the k-th diagonal of the output. kint, optional Diagonal to set; 0, the default, corresponds to the “main” diagonal, a positive (negative) k giving the number of the diagonal above (below) the main. Returns outndarray The 2-D output array. See also diag MATLAB work-alike for 1-D and 2-D arrays. diagonal Return specified diagonals. trace Sum along diagonals. Examples >>> np.diagflat([[1,2], [3,4]]) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) >>> np.diagflat([1,2], 1) array([[0, 1, 0], [0, 0, 2], [0, 0, 0]])
numpy.reference.generated.numpy.diagflat
numpy.diagonal numpy.diagonal(a, offset=0, axis1=0, axis2=1)[source] Return specified diagonals. If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals. In versions of NumPy prior to 1.7, this function always returned a new, independent array containing a copy of the values in the diagonal. In NumPy 1.7 and 1.8, it continues to return a copy of the diagonal, but depending on this fact is deprecated. Writing to the resulting array continues to work as it used to, but a FutureWarning is issued. Starting in NumPy 1.9 it returns a read-only view on the original array. Attempting to write to the resulting array will produce an error. In some future release, it will return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array. If you don’t write to the array returned by this function, then you can just ignore all of the above. If you depend on the current behavior, then we suggest copying the returned array explicitly, i.e., use np.diagonal(a).copy() instead of just np.diagonal(a). This will work with both past and future versions of NumPy. Parameters aarray_like Array from which the diagonals are taken. offsetint, optional Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal (0). axis1int, optional Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0). axis2int, optional Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis (1). Returns array_of_diagonalsndarray If a is 2-D, then a 1-D array containing the diagonal and of the same type as a is returned unless a is a matrix, in which case a 1-D array rather than a (2-D) matrix is returned in order to maintain backward compatibility. If a.ndim > 2, then the dimensions specified by axis1 and axis2 are removed, and a new axis inserted at the end corresponding to the diagonal. Raises ValueError If the dimension of a is less than 2. See also diag MATLAB work-a-like for 1-D and 2-D arrays. diagflat Create diagonal arrays. trace Sum along diagonals. Examples >>> a = np.arange(4).reshape(2,2) >>> a array([[0, 1], [2, 3]]) >>> a.diagonal() array([0, 3]) >>> a.diagonal(1) array([1]) A 3-D example: >>> a = np.arange(8).reshape(2,2,2); a array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> a.diagonal(0, # Main diagonals of two arrays created by skipping ... 0, # across the outer(left)-most axis last and ... 1) # the "middle" (row) axis first. array([[0, 6], [1, 7]]) The sub-arrays whose main diagonals we just obtained; note that each corresponds to fixing the right-most (column) axis, and that the diagonals are “packed” in rows. >>> a[:,:,0] # main diagonal is [0 6] array([[0, 2], [4, 6]]) >>> a[:,:,1] # main diagonal is [1 7] array([[1, 3], [5, 7]]) The anti-diagonal can be obtained by reversing the order of elements using either numpy.flipud or numpy.fliplr. >>> a = np.arange(9).reshape(3, 3) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.fliplr(a).diagonal() # Horizontal flip array([2, 4, 6]) >>> np.flipud(a).diagonal() # Vertical flip array([6, 4, 2]) Note that the order in which the diagonal is retrieved varies depending on the flip function.
numpy.reference.generated.numpy.diagonal
numpy.diff numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)[source] Calculate the n-th discrete difference along the given axis. The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively. Parameters aarray_like Input array nint, optional The number of times values are differenced. If zero, the input is returned as-is. axisint, optional The axis along which the difference is taken, default is the last axis. prepend, appendarray_like, optional Values to prepend or append to a along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array in along all other axes. Otherwise the dimension and shape must match a except along axis. New in version 1.16.0. Returns diffndarray The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. The type of the output is the same as the type of the difference between any two elements of a. This is the same as the type of a in most cases. A notable exception is datetime64, which results in a timedelta64 output array. See also gradient, ediff1d, cumsum Notes Type is preserved for boolean arrays, so the result will contain False when consecutive elements are the same and True when they differ. For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly: >>> u8_arr = np.array([1, 0], dtype=np.uint8) >>> np.diff(u8_arr) array([255], dtype=uint8) >>> u8_arr[1,...] - u8_arr[0,...] 255 If this is not desirable, then the array should be cast to a larger integer type first: >>> i16_arr = u8_arr.astype(np.int16) >>> np.diff(i16_arr) array([-1], dtype=int16) Examples >>> x = np.array([1, 2, 4, 7, 0]) >>> np.diff(x) array([ 1, 2, 3, -7]) >>> np.diff(x, n=2) array([ 1, 1, -10]) >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> np.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> np.diff(x, axis=0) array([[-1, 2, 0, -2]]) >>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64) >>> np.diff(x) array([1, 1], dtype='timedelta64[D]')
numpy.reference.generated.numpy.diff
numpy.digitize numpy.digitize(x, bins, right=False)[source] Return the indices of the bins to which each value in input array belongs. right order of bins returned index i satisfies False increasing bins[i-1] <= x < bins[i] True increasing bins[i-1] < x <= bins[i] False decreasing bins[i-1] > x >= bins[i] True decreasing bins[i-1] >= x > bins[i] If values in x are beyond the bounds of bins, 0 or len(bins) is returned as appropriate. Parameters xarray_like Input array to be binned. Prior to NumPy 1.10.0, this array had to be 1-dimensional, but can now have any shape. binsarray_like Array of bins. It has to be 1-dimensional and monotonic. rightbool, optional Indicating whether the intervals include the right or the left bin edge. Default behavior is (right==False) indicating that the interval does not include the right edge. The left bin end is open in this case, i.e., bins[i-1] <= x < bins[i] is the default behavior for monotonically increasing bins. Returns indicesndarray of ints Output array of indices, of same shape as x. Raises ValueError If bins is not monotonic. TypeError If the type of the input is complex. See also bincount, histogram, unique, searchsorted Notes If values in x are such that they fall outside the bin range, attempting to index bins with the indices that digitize returns will result in an IndexError. New in version 1.10.0. np.digitize is implemented in terms of np.searchsorted. This means that a binary search is used to bin the values, which scales much better for larger number of bins than the previous linear search. It also removes the requirement for the input array to be 1-dimensional. For monotonically _increasing_ bins, the following are equivalent: np.digitize(x, bins, right=True) np.searchsorted(bins, x, side='left') Note that as the order of the arguments are reversed, the side must be too. The searchsorted call is marginally faster, as it does not do any monotonicity checks. Perhaps more importantly, it supports all dtypes. Examples >>> x = np.array([0.2, 6.4, 3.0, 1.6]) >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0]) >>> inds = np.digitize(x, bins) >>> inds array([1, 4, 3, 2]) >>> for n in range(x.size): ... print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]]) ... 0.0 <= 0.2 < 1.0 4.0 <= 6.4 < 10.0 2.5 <= 3.0 < 4.0 1.0 <= 1.6 < 2.5 >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.]) >>> bins = np.array([0, 5, 10, 15, 20]) >>> np.digitize(x,bins,right=True) array([1, 2, 3, 4, 4]) >>> np.digitize(x,bins,right=False) array([1, 3, 3, 4, 5])
numpy.reference.generated.numpy.digitize
numpy.disp numpy.disp(mesg, device=None, linefeed=True)[source] Display a message on a device. Parameters mesgstr Message to display. deviceobject Device to write message. If None, defaults to sys.stdout which is very similar to print. device needs to have write() and flush() methods. linefeedbool, optional Option whether to print a line feed or not. Defaults to True. Raises AttributeError If device does not have a write() or flush() method. Examples Besides sys.stdout, a file-like object can also be used as it has both required methods: >>> from io import StringIO >>> buf = StringIO() >>> np.disp(u'"Display" in a file', device=buf) >>> buf.getvalue() '"Display" in a file\n'
numpy.reference.generated.numpy.disp
numpy.distutils.ccompiler Functions CCompiler_compile(self, sources[, ...]) Compile one or more source files. CCompiler_customize(self, dist[, need_cxx]) Do any platform-specific customization of a compiler instance. CCompiler_customize_cmd(self, cmd[, ignore]) Customize compiler using distutils command. CCompiler_cxx_compiler(self) Return the C++ compiler. CCompiler_find_executables(self) Does nothing here, but is called by the get_version method and can be overridden by subclasses. CCompiler_get_version(self[, force, ok_status]) Return compiler version, or None if compiler is not available. CCompiler_object_filenames(self, ...[, ...]) Return the name of the object files for the given source files. CCompiler_show_customization(self) Print the compiler customizations to stdout. CCompiler_spawn(self, cmd[, display, env]) Execute a command in a sub-process. gen_lib_options(compiler, library_dirs, ...) new_compiler([plat, compiler, verbose, ...]) replace_method(klass, method_name, func) simple_version_match([pat, ignore, start]) Simple matching of version numbers, for use in CCompiler and FCompiler.
numpy.reference.generated.numpy.distutils.ccompiler
numpy.distutils.ccompiler_opt Provides the CCompilerOpt class, used for handling the CPU/hardware optimization, starting from parsing the command arguments, to managing the relation between the CPU baseline and dispatch-able features, also generating the required C headers and ending with compiling the sources with proper compiler’s flags. CCompilerOpt doesn’t provide runtime detection for the CPU features, instead only focuses on the compiler side, but it creates abstract C headers that can be used later for the final runtime dispatching process. Functions new_ccompiler_opt(compiler, dispatch_hpath, ...) Create a new instance of 'CCompilerOpt' and generate the dispatch header which contains the #definitions and headers of platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features. Classes CCompilerOpt(ccompiler[, cpu_baseline, ...]) A helper class for CCompiler aims to provide extra build options to effectively control of compiler optimizations that are directly related to CPU features.
numpy.reference.generated.numpy.distutils.ccompiler_opt
numpy.distutils.ccompiler_opt.CCompilerOpt class numpy.distutils.ccompiler_opt.CCompilerOpt(ccompiler, cpu_baseline='min', cpu_dispatch='max', cache_path=None)[source] A helper class for CCompiler aims to provide extra build options to effectively control of compiler optimizations that are directly related to CPU features. Attributes conf_cache_factors conf_tmp_path Methods cache_flush() Force update the cache. cc_normalize_flags(flags) Remove the conflicts that caused due gathering implied features flags. conf_features_partial() Return a dictionary of supported CPU features by the platform, and accumulate the rest of undefined options in conf_features, the returned dict has same rules and notes in class attribute conf_features, also its override any options that been set in 'conf_features'. cpu_baseline_flags() Returns a list of final CPU baseline compiler flags cpu_baseline_names() return a list of final CPU baseline feature names cpu_dispatch_names() return a list of final CPU dispatch feature names dist_compile(sources, flags[, ccompiler]) Wrap CCompiler.compile() dist_error(*args) Raise a compiler error dist_fatal(*args) Raise a distutils error dist_info() Return a tuple containing info about (platform, compiler, extra_args), required by the abstract class '_CCompiler' for discovering the platform environment. dist_load_module(name, path) Load a module from file, required by the abstract class '_Cache'. dist_log(*args[, stderr]) Print a console message dist_test(source, flags[, macros]) Return True if 'CCompiler.compile()' able to compile a source file with certain flags. feature_ahead(names) Return list of features in 'names' after remove any implied features and keep the origins. feature_c_preprocessor(feature_name[, tabs]) Generate C preprocessor definitions and include headers of a CPU feature. feature_detect(names) Return a list of CPU features that required to be detected sorted from the lowest to highest interest. feature_get_til(names, keyisfalse) same as feature_implies_c() but stop collecting implied features when feature's option that provided through parameter 'keyisfalse' is False, also sorting the returned features. feature_implies(names[, keep_origins]) Return a set of CPU features that implied by 'names' feature_implies_c(names) same as feature_implies() but combining 'names' feature_is_exist(name) Returns True if a certain feature is exist and covered within _Config.conf_features. feature_names([names, force_flags, macros]) Returns a set of CPU feature names that supported by platform and the C compiler. feature_sorted(names[, reverse]) Sort a list of CPU features ordered by the lowest interest. feature_untied(names) same as 'feature_ahead()' but if both features implied each other and keep the highest interest. generate_dispatch_header(header_path) Generate the dispatch header which contains the #definitions and headers for platform-specific instruction-sets for the enabled CPU baseline and dispatch-able features. is_cached() Returns True if the class loaded from the cache file me(cb) A static method that can be treated as a decorator to dynamically cache certain methods. parse_targets(source) Fetch and parse configuration statements that required for defining the targeted CPU features, statements should be declared in the top of source in between C comment and start with a special mark @targets. try_dispatch(sources[, src_dir, ccompiler]) Compile one or more dispatch-able sources and generates object files, also generates abstract C config headers and macros that used later for the final runtime dispatching process. cache_hash cc_test_flags feature_can_autovec feature_extra_checks feature_flags feature_is_supported feature_test report
numpy.reference.generated.numpy.distutils.ccompiler_opt.ccompileropt
numpy.distutils.core.Extension class numpy.distutils.core.Extension(name, sources, include_dirs=None, define_macros=None, undef_macros=None, library_dirs=None, libraries=None, runtime_library_dirs=None, extra_objects=None, extra_compile_args=None, extra_link_args=None, export_symbols=None, swig_opts=None, depends=None, language=None, f2py_options=None, module_dirs=None, extra_c_compile_args=None, extra_cxx_compile_args=None, extra_f77_compile_args=None, extra_f90_compile_args=None)[source] Parameters namestr Extension name. sourceslist of str List of source file locations relative to the top directory of the package. extra_compile_argslist of str Extra command line arguments to pass to the compiler. extra_f77_compile_argslist of str Extra command line arguments to pass to the fortran77 compiler. extra_f90_compile_argslist of str Extra command line arguments to pass to the fortran90 compiler. Methods has_cxx_sources has_f2py_sources
numpy.reference.generated.numpy.distutils.core.extension
distutils.misc_util numpy.distutils.misc_util.all_strings(lst)[source] Return True if all items in lst are string objects. numpy.distutils.misc_util.allpath(name)[source] Convert a /-separated pathname to one using the OS’s path separator. numpy.distutils.misc_util.appendpath(prefix, path)[source] numpy.distutils.misc_util.as_list(seq)[source] numpy.distutils.misc_util.blue_text(s)[source] numpy.distutils.misc_util.cyan_text(s)[source] numpy.distutils.misc_util.cyg2win32(path: str) → str[source] Convert a path from Cygwin-native to Windows-native. Uses the cygpath utility (part of the Base install) to do the actual conversion. Falls back to returning the original path if this fails. Handles the default /cygdrive mount prefix as well as the /proc/cygdrive portable prefix, custom cygdrive prefixes such as / or /mnt, and absolute paths such as /usr/src/ or /home/username Parameters pathstr The path to convert Returns converted_pathstr The converted path Notes Documentation for cygpath utility: https://cygwin.com/cygwin-ug-net/cygpath.html Documentation for the C function it wraps: https://cygwin.com/cygwin-api/func-cygwin-conv-path.html numpy.distutils.misc_util.default_config_dict(name=None, parent_name=None, local_path=None)[source] Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py. numpy.distutils.misc_util.dict_append(d, **kws)[source] numpy.distutils.misc_util.dot_join(*args)[source] numpy.distutils.misc_util.exec_mod_from_location(modname, modfile)[source] Use importlib machinery to import a module modname from the file modfile. Depending on the spec.loader, the module may not be registered in sys.modules. numpy.distutils.misc_util.filter_sources(sources)[source] Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively. numpy.distutils.misc_util.generate_config_py(target)[source] Generate config.py file containing system_info information used during building the package. Usage: config[‘py_modules’].append((packagename, ‘__config__’,generate_config_py)) numpy.distutils.misc_util.get_build_architecture()[source] numpy.distutils.misc_util.get_cmd(cmdname, _cache={})[source] numpy.distutils.misc_util.get_data_files(data)[source] numpy.distutils.misc_util.get_dependencies(sources)[source] numpy.distutils.misc_util.get_ext_source_files(ext)[source] numpy.distutils.misc_util.get_frame(level=0)[source] Return frame object from call stack with given level. numpy.distutils.misc_util.get_info(pkgname, dirs=None)[source] Return an info dict for a given C library. The info dict contains the necessary options to use the C library. Parameters pkgnamestr Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirssequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns infodict The dictionary with build information. Raises PkgNotFound If the package is not found. See also Configuration.add_npy_pkg_config, Configuration.add_installed_library get_pkg_info Examples To get the necessary information for the npymath library from NumPy: >>> npymath_info = np.distutils.misc_util.get_info('npymath') >>> npymath_info {'define_macros': [], 'libraries': ['npymath'], 'library_dirs': ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']} This info dict can then be used as input to a Configuration instance: config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info) numpy.distutils.misc_util.get_language(sources)[source] Determine language value (c,f77,f90) from sources numpy.distutils.misc_util.get_lib_source_files(lib)[source] numpy.distutils.misc_util.get_mathlibs(path=None)[source] Return the MATHLIB line from numpyconfig.h numpy.distutils.misc_util.get_num_build_jobs()[source] Get number of parallel build jobs set by the –parallel command line argument of setup.py If the command did not receive a setting the environment variable NPY_NUM_BUILD_JOBS is checked. If that is unset, return the number of processors on the system, with a maximum of 8 (to prevent overloading the system if there a lot of CPUs). Returns outint number of parallel jobs that can be run numpy.distutils.misc_util.get_numpy_include_dirs()[source] numpy.distutils.misc_util.get_pkg_info(pkgname, dirs=None)[source] Return library info for the given package. Parameters pkgnamestr Name of the package (should match the name of the .ini file, without the extension, e.g. foo for the file foo.ini). dirssequence, optional If given, should be a sequence of additional directories where to look for npy-pkg-config files. Those directories are searched prior to the NumPy directory. Returns pkginfoclass instance The LibraryInfo instance containing the build information. Raises PkgNotFound If the package is not found. See also Configuration.add_npy_pkg_config, Configuration.add_installed_library get_info numpy.distutils.misc_util.get_script_files(scripts)[source] numpy.distutils.misc_util.gpaths(paths, local_path='', include_non_existing=True)[source] Apply glob to paths and prepend local_path if needed. numpy.distutils.misc_util.green_text(s)[source] numpy.distutils.misc_util.has_cxx_sources(sources)[source] Return True if sources contains C++ files numpy.distutils.misc_util.has_f_sources(sources)[source] Return True if sources contains Fortran files numpy.distutils.misc_util.is_local_src_dir(directory)[source] Return true if directory is local directory. numpy.distutils.misc_util.is_sequence(seq)[source] numpy.distutils.misc_util.is_string(s)[source] numpy.distutils.misc_util.mingw32()[source] Return true when using mingw32 environment. numpy.distutils.misc_util.minrelpath(path)[source] Resolve and ‘.’ from path. numpy.distutils.misc_util.njoin(*path)[source] Join two or more pathname components + - convert a /-separated pathname to one using the OS’s path separator. - resolve and from path. Either passing n arguments as in njoin(‘a’,’b’), or a sequence of n names as in njoin([‘a’,’b’]) is handled, or a mixture of such arguments. numpy.distutils.misc_util.red_text(s)[source] numpy.distutils.misc_util.sanitize_cxx_flags(cxxflags)[source] Some flags are valid for C but not C++. Prune them. numpy.distutils.misc_util.terminal_has_colors()[source] numpy.distutils.misc_util.yellow_text(s)[source]
numpy.reference.distutils.misc_util
numpy.distutils.misc_util.allpath(name)[source] Convert a /-separated pathname to one using the OS’s path separator.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.allpath
numpy.distutils.misc_util.appendpath(prefix, path)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.appendpath
numpy.distutils.misc_util.as_list(seq)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.as_list
numpy.distutils.misc_util.blue_text(s)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.blue_text
numpy.distutils.misc_util.cyan_text(s)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.cyan_text
numpy.distutils.misc_util.cyg2win32(path: str) → str[source] Convert a path from Cygwin-native to Windows-native. Uses the cygpath utility (part of the Base install) to do the actual conversion. Falls back to returning the original path if this fails. Handles the default /cygdrive mount prefix as well as the /proc/cygdrive portable prefix, custom cygdrive prefixes such as / or /mnt, and absolute paths such as /usr/src/ or /home/username Parameters pathstr The path to convert Returns converted_pathstr The converted path Notes Documentation for cygpath utility: https://cygwin.com/cygwin-ug-net/cygpath.html Documentation for the C function it wraps: https://cygwin.com/cygwin-api/func-cygwin-conv-path.html
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.cyg2win32
numpy.distutils.misc_util.default_config_dict(name=None, parent_name=None, local_path=None)[source] Return a configuration dictionary for usage in configuration() function defined in file setup_<name>.py.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.default_config_dict
numpy.distutils.misc_util.dict_append(d, **kws)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.dict_append
numpy.distutils.misc_util.dot_join(*args)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.dot_join
numpy.distutils.misc_util.exec_mod_from_location(modname, modfile)[source] Use importlib machinery to import a module modname from the file modfile. Depending on the spec.loader, the module may not be registered in sys.modules.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.exec_mod_from_location
numpy.distutils.misc_util.filter_sources(sources)[source] Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively.
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.filter_sources
numpy.distutils.misc_util.generate_config_py(target)[source] Generate config.py file containing system_info information used during building the package. Usage: config[‘py_modules’].append((packagename, ‘__config__’,generate_config_py))
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.generate_config_py
numpy.distutils.misc_util.get_build_architecture()[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_build_architecture
numpy.distutils.misc_util.get_cmd(cmdname, _cache={})[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_cmd
numpy.distutils.misc_util.get_data_files(data)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_data_files
numpy.distutils.misc_util.get_dependencies(sources)[source]
numpy.reference.distutils.misc_util#numpy.distutils.misc_util.get_dependencies