doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.r_ numpy.r_ = <numpy.lib.index_tricks.RClass object> Translates slice objects to concatenation along the first axis. This is a simple way to build up arrays quickly. There are two use cases. If the index expression contains comma separated arrays, then stack them along their first axis. If the index expression contains slice notation or scalars then create a 1-D array with a range indicated by the slice notation. If slice notation is used, the syntax start:stop:step is equivalent to np.arange(start, stop, step) inside of the brackets. However, if step is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive. In other words start:stop:stepj is interpreted as np.linspace(start, stop, step, endpoint=1) inside of the brackets. After expansion of slice notation, all comma separated sequences are concatenated together. Optional character strings placed as the first element of the index expression can be used to change the output. The strings ‘r’ or ‘c’ result in matrix output. If the result is 1-D and ‘r’ is specified a 1 x N (row) matrix is produced. If the result is 1-D and ‘c’ is specified, then a N x 1 (column) matrix is produced. If the result is 2-D then both provide the same matrix result. A string integer specifies which axis to stack multiple comma separated arrays along. A string of two comma-separated integers allows indication of the minimum number of dimensions to force each entry into as the second integer (the axis to concatenate along is still the first integer). A string with three comma-separated integers allows specification of the axis to concatenate along, the minimum number of dimensions to force the entries to, and which axis should contain the start of the arrays which are less than the specified number of dimensions. In other words the third integer allows you to specify where the 1’s should be placed in the shape of the arrays that have their shapes upgraded. By default, they are placed in the front of the shape tuple. The third argument allows you to specify where the start of the array should be instead. Thus, a third argument of ‘0’ would place the 1’s at the end of the array shape. Negative integers specify where in the new shape tuple the last dimension of upgraded arrays should be placed, so the default is ‘-1’. Parameters Not a function, so takes no parameters Returns A concatenated ndarray or matrix. See also concatenate Join a sequence of arrays along an existing axis. c_ Translates slice objects to concatenation along the second axis. Examples >>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])] array([1, 2, 3, ..., 4, 5, 6]) >>> np.r_[-1:1:6j, [0]*3, 5, 6] array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ]) String integers specify the axis to concatenate along or the minimum number of dimensions to force entries into. >>> a = np.array([[0, 1, 2], [3, 4, 5]]) >>> np.r_['-1', a, a] # concatenate along last axis array([[0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5]]) >>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2 array([[1, 2, 3], [4, 5, 6]]) >>> np.r_['0,2,0', [1,2,3], [4,5,6]] array([[1], [2], [3], [4], [5], [6]]) >>> np.r_['1,2,0', [1,2,3], [4,5,6]] array([[1, 4], [2, 5], [3, 6]]) Using ‘r’ or ‘c’ as a first string argument creates a matrix. >>> np.r_['r',[1,2,3], [4,5,6]] matrix([[1, 2, 3, 4, 5, 6]])
numpy.reference.generated.numpy.r_
numpy.rad2deg numpy.rad2deg(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'rad2deg'> Convert angles from radians to degrees. Parameters xarray_like Angle 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 angle in degrees. This is a scalar if x is a scalar. See also deg2rad Convert angles from degrees to radians. unwrap Remove large jumps in angle by wrapping. Notes New in version 1.3.0. rad2deg(x) is 180 * x / pi. Examples >>> np.rad2deg(np.pi/2) 90.0
numpy.reference.generated.numpy.rad2deg
numpy.radians numpy.radians(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'radians'> Convert angles from degrees to radians. Parameters xarray_like Input array 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 radian values. This is a scalar if x is a scalar. See also deg2rad equivalent function Examples Convert a degree array to radians >>> deg = np.arange(12.) * 30. >>> np.radians(deg) array([ 0. , 0.52359878, 1.04719755, 1.57079633, 2.0943951 , 2.61799388, 3.14159265, 3.66519143, 4.1887902 , 4.71238898, 5.23598776, 5.75958653]) >>> out = np.zeros((deg.shape)) >>> ret = np.radians(deg, out) >>> ret is out True
numpy.reference.generated.numpy.radians
numpy.random.BitGenerator class numpy.random.BitGenerator(seed=None) Base Class for generic BitGenerators, which provide a stream of random bits based on different algorithms. Must be overridden. Parameters seed{None, int, array_like[ints], SeedSequence}, optional A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to ~`numpy.random.SeedSequence` to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. See also SeedSequence Attributes lockthreading.Lock Lock instance that is shared so that the same BitGenerator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock. Methods random_raw(self[, size]) Return randoms as generated by the underlying BitGenerator
numpy.reference.random.bit_generators.generated.numpy.random.bitgenerator
Random Generator The Generator provides access to a wide range of distributions, and served as a replacement for RandomState. The main difference between the two is that Generator relies on an additional BitGenerator to manage state and generate the random bits, which are then transformed into random values from useful distributions. The default BitGenerator used by Generator is PCG64. The BitGenerator can be changed by passing an instantized BitGenerator to Generator. numpy.random.default_rng() Construct a new Generator with the default BitGenerator (PCG64). Parameters seed{None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Additionally, when passed a BitGenerator, it will be wrapped by Generator. If passed a Generator, it will be returned unaltered. Returns Generator The initialized generator object. Notes If seed is not a BitGenerator or a Generator, a new BitGenerator is instantiated. This function does not manage a default global instance. Examples default_rng is the recommended constructor for the random number class Generator. Here are several ways we can construct a random number generator using default_rng and the Generator class. Here we use default_rng to generate a random float: >>> import numpy as np >>> rng = np.random.default_rng(12345) >>> print(rng) Generator(PCG64) >>> rfloat = rng.random() >>> rfloat 0.22733602246716966 >>> type(rfloat) <class 'float'> Here we use default_rng to generate 3 random integers between 0 (inclusive) and 10 (exclusive): >>> import numpy as np >>> rng = np.random.default_rng(12345) >>> rints = rng.integers(low=0, high=10, size=3) >>> rints array([6, 2, 7]) >>> type(rints[0]) <class 'numpy.int64'> Here we specify a seed so that we have reproducible results: >>> import numpy as np >>> rng = np.random.default_rng(seed=42) >>> print(rng) Generator(PCG64) >>> arr1 = rng.random((3, 3)) >>> arr1 array([[0.77395605, 0.43887844, 0.85859792], [0.69736803, 0.09417735, 0.97562235], [0.7611397 , 0.78606431, 0.12811363]]) If we exit and restart our Python interpreter, we’ll see that we generate the same random numbers again: >>> import numpy as np >>> rng = np.random.default_rng(seed=42) >>> arr2 = rng.random((3, 3)) >>> arr2 array([[0.77395605, 0.43887844, 0.85859792], [0.69736803, 0.09417735, 0.97562235], [0.7611397 , 0.78606431, 0.12811363]]) class numpy.random.Generator(bit_generator) Container for the BitGenerators. Generator exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned. The function numpy.random.default_rng will instantiate a Generator with numpy’s default BitGenerator. No Compatibility Guarantee Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change. Parameters bit_generatorBitGenerator BitGenerator to use as the core generator. See also default_rng Recommended constructor for Generator. Notes The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator. It uses Mersenne Twister, and this bit generator can be accessed using MT19937. Generator, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from. Examples >>> from numpy.random import Generator, PCG64 >>> rng = Generator(PCG64()) >>> rng.standard_normal() -0.203 # random Accessing the BitGenerator bit_generator Gets the bit generator instance used by the generator Simple random data integers(low[, high, size, dtype, endpoint]) Return random integers from low (inclusive) to high (exclusive), or if endpoint=True, low (inclusive) to high (inclusive). random([size, dtype, out]) Return random floats in the half-open interval [0.0, 1.0). choice(a[, size, replace, p, axis, shuffle]) Generates a random sample from a given array bytes(length) Return random bytes. Permutations The methods for randomly permuting a sequence are shuffle(x[, axis]) Modify an array or sequence in-place by shuffling its contents. permutation(x[, axis]) Randomly permute a sequence, or return a permuted range. permuted(x[, axis, out]) Randomly permute x along axis axis. The following table summarizes the behaviors of the methods. method copy/in-place axis handling shuffle in-place as if 1d permutation copy as if 1d permuted either (use ‘out’ for in-place) axis independent The following subsections provide more details about the differences. In-place vs. copy The main difference between Generator.shuffle and Generator.permutation is that Generator.shuffle operates in-place, while Generator.permutation returns a copy. By default, Generator.permuted returns a copy. To operate in-place with Generator.permuted, pass the same array as the first argument and as the value of the out parameter. For example, >>> rng = np.random.default_rng() >>> x = np.arange(0, 15).reshape(3, 5) >>> x array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> y = rng.permuted(x, axis=1, out=x) >>> x array([[ 1, 0, 2, 4, 3], # random [ 6, 7, 8, 9, 5], [10, 14, 11, 13, 12]]) Note that when out is given, the return value is out: >>> y is x True Handling the axis parameter An important distinction for these methods is how they handle the axis parameter. Both Generator.shuffle and Generator.permutation treat the input as a one-dimensional sequence, and the axis parameter determines which dimension of the input array to use as the sequence. In the case of a two-dimensional array, axis=0 will, in effect, rearrange the rows of the array, and axis=1 will rearrange the columns. For example >>> rng = np.random.default_rng() >>> x = np.arange(0, 15).reshape(3, 5) >>> x array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> rng.permutation(x, axis=1) array([[ 1, 3, 2, 0, 4], # random [ 6, 8, 7, 5, 9], [11, 13, 12, 10, 14]]) Note that the columns have been rearranged “in bulk”: the values within each column have not changed. The method Generator.permuted treats the axis parameter similar to how numpy.sort treats it. Each slice along the given axis is shuffled independently of the others. Compare the following example of the use of Generator.permuted to the above example of Generator.permutation: >>> rng.permuted(x, axis=1) array([[ 1, 0, 2, 4, 3], # random [ 5, 7, 6, 9, 8], [10, 14, 12, 13, 11]]) In this example, the values within each row (i.e. the values along axis=1) have been shuffled independently. This is not a “bulk” shuffle of the columns. Shuffling non-NumPy sequences Generator.shuffle works on non-NumPy sequences. That is, if it is given a sequence that is not a NumPy array, it shuffles that sequence in-place. For example, >>> rng = np.random.default_rng() >>> a = ['A', 'B', 'C', 'D', 'E'] >>> rng.shuffle(a) # shuffle the list in-place >>> a ['B', 'D', 'A', 'E', 'C'] # random Distributions beta(a, b[, size]) Draw samples from a Beta distribution. binomial(n, p[, size]) Draw samples from a binomial distribution. chisquare(df[, size]) Draw samples from a chi-square distribution. dirichlet(alpha[, size]) Draw samples from the Dirichlet distribution. exponential([scale, size]) Draw samples from an exponential distribution. f(dfnum, dfden[, size]) Draw samples from an F distribution. gamma(shape[, scale, size]) Draw samples from a Gamma distribution. geometric(p[, size]) Draw samples from the geometric distribution. gumbel([loc, scale, size]) Draw samples from a Gumbel distribution. hypergeometric(ngood, nbad, nsample[, size]) Draw samples from a Hypergeometric distribution. laplace([loc, scale, size]) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay). logistic([loc, scale, size]) Draw samples from a logistic distribution. lognormal([mean, sigma, size]) Draw samples from a log-normal distribution. logseries(p[, size]) Draw samples from a logarithmic series distribution. multinomial(n, pvals[, size]) Draw samples from a multinomial distribution. multivariate_hypergeometric(colors, nsample) Generate variates from a multivariate hypergeometric distribution. multivariate_normal(mean, cov[, size, ...]) Draw random samples from a multivariate normal distribution. negative_binomial(n, p[, size]) Draw samples from a negative binomial distribution. noncentral_chisquare(df, nonc[, size]) Draw samples from a noncentral chi-square distribution. noncentral_f(dfnum, dfden, nonc[, size]) Draw samples from the noncentral F distribution. normal([loc, scale, size]) Draw random samples from a normal (Gaussian) distribution. pareto(a[, size]) Draw samples from a Pareto II or Lomax distribution with specified shape. poisson([lam, size]) Draw samples from a Poisson distribution. power(a[, size]) Draws samples in [0, 1] from a power distribution with positive exponent a - 1. rayleigh([scale, size]) Draw samples from a Rayleigh distribution. standard_cauchy([size]) Draw samples from a standard Cauchy distribution with mode = 0. standard_exponential([size, dtype, method, out]) Draw samples from the standard exponential distribution. standard_gamma(shape[, size, dtype, out]) Draw samples from a standard Gamma distribution. standard_normal([size, dtype, out]) Draw samples from a standard Normal distribution (mean=0, stdev=1). standard_t(df[, size]) Draw samples from a standard Student's t distribution with df degrees of freedom. triangular(left, mode, right[, size]) Draw samples from the triangular distribution over the interval [left, right]. uniform([low, high, size]) Draw samples from a uniform distribution. vonmises(mu, kappa[, size]) Draw samples from a von Mises distribution. wald(mean, scale[, size]) Draw samples from a Wald, or inverse Gaussian, distribution. weibull(a[, size]) Draw samples from a Weibull distribution. zipf(a[, size]) Draw samples from a Zipf distribution.
numpy.reference.random.generator
class numpy.random.Generator(bit_generator) Container for the BitGenerators. Generator exposes a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned. The function numpy.random.default_rng will instantiate a Generator with numpy’s default BitGenerator. No Compatibility Guarantee Generator does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change. Parameters bit_generatorBitGenerator BitGenerator to use as the core generator. See also default_rng Recommended constructor for Generator. Notes The Python stdlib module random contains pseudo-random number generator with a number of methods that are similar to the ones available in Generator. It uses Mersenne Twister, and this bit generator can be accessed using MT19937. Generator, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from. Examples >>> from numpy.random import Generator, PCG64 >>> rng = Generator(PCG64()) >>> rng.standard_normal() -0.203 # random
numpy.reference.random.generator#numpy.random.Generator
Mersenne Twister (MT19937) class numpy.random.MT19937(seed=None) Container for the Mersenne Twister pseudo-random number generator. Parameters seed{None, int, array_like[ints], SeedSequence}, optional A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Notes MT19937 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers [1]. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator. State and Seeding The MT19937 state vector consists of a 624-element array of 32-bit unsigned integers plus a single integer value between 0 and 624 that indexes the current position within the main array. The input seed is processed by SeedSequence to fill the whole state. The first element is reset such that only its most significant bit is set. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, MT19937, SeedSequence >>> sg = SeedSequence(1234) >>> rg = [Generator(MT19937(s)) for s in sg.spawn(10)] Another method is to use MT19937.jumped which advances the state as-if \(2^{128}\) random numbers have been generated ([1], [2]). This allows the original sequence to be split so that distinct segments can be used in each worker process. All generators should be chained to ensure that the segments come from the same sequence. >>> from numpy.random import Generator, MT19937, SeedSequence >>> sg = SeedSequence(1234) >>> bit_generator = MT19937(sg) >>> rg = [] >>> for _ in range(10): ... rg.append(Generator(bit_generator)) ... # Chain the BitGenerators ... bit_generator = bit_generator.jumped() Compatibility Guarantee MT19937 makes a guarantee that a fixed seed and will always produce the same random integer stream. References 1(1,2) Hiroshi Haramoto, Makoto Matsumoto, and Pierre L’Ecuyer, “A Fast Jump Ahead Algorithm for Linear Recurrences in a Polynomial Space”, Sequences and Their Applications - SETA, 290–298, 2008. 2 Hiroshi Haramoto, Makoto Matsumoto, Takuji Nishimura, François Panneton, Pierre L’Ecuyer, “Efficient Jump Ahead for F2-Linear Random Number Generators”, INFORMS JOURNAL ON COMPUTING, Vol. 20, No. 3, Summer 2008, pp. 385-390. Attributes lock: threading.Lock Lock instance that is shared so that the same bit git generator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock. State state Get or set the PRNG state Parallel generation jumped([jumps]) Returns a new bit generator with the state jumped Extending cffi CFFI interface ctypes ctypes interface
numpy.reference.random.bit_generators.mt19937
Permuted Congruential Generator (64-bit, PCG64) class numpy.random.PCG64(seed=None) BitGenerator for the PCG-64 pseudo-random number generator. Parameters seed{None, int, array_like[ints], SeedSequence}, optional A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Notes PCG-64 is a 128-bit implementation of O’Neill’s permutation congruential generator ([1], [2]). PCG-64 has a period of \(2^{128}\) and supports advancing an arbitrary number of steps as well as \(2^{127}\) streams. The specific member of the PCG family that we use is PCG XSL RR 128/64 as described in the paper ([2]). PCG64 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. Supports the method advance to advance the RNG an arbitrary number of steps. The state of the PCG-64 RNG is represented by 2 128-bit unsigned integers. State and Seeding The PCG64 state vector consists of 2 unsigned 128-bit values, which are represented externally as Python ints. One is the state of the PRNG, which is advanced by a linear congruential generator (LCG). The second is a fixed odd increment used in the LCG. The input seed is processed by SeedSequence to generate both values. The increment is not independently settable. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, PCG64, SeedSequence >>> sg = SeedSequence(1234) >>> rg = [Generator(PCG64(s)) for s in sg.spawn(10)] Compatibility Guarantee PCG64 makes a guarantee that a fixed seed will always produce the same random integer stream. References 1 “PCG, A Family of Better Random Number Generators” 2(1,2) O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation” State state Get or set the PRNG state Parallel generation advance(delta) Advance the underlying RNG as-if delta draws have occurred. jumped([jumps]) Returns a new bit generator with the state jumped. Extending cffi CFFI interface ctypes ctypes interface
numpy.reference.random.bit_generators.pcg64
Permuted Congruential Generator (64-bit, PCG64 DXSM) class numpy.random.PCG64DXSM(seed=None) BitGenerator for the PCG-64 DXSM pseudo-random number generator. Parameters seed{None, int, array_like[ints], SeedSequence}, optional A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Notes PCG-64 DXSM is a 128-bit implementation of O’Neill’s permutation congruential generator ([1], [2]). PCG-64 DXSM has a period of \(2^{128}\) and supports advancing an arbitrary number of steps as well as \(2^{127}\) streams. The specific member of the PCG family that we use is PCG CM DXSM 128/64. It differs from PCG64 in that it uses the stronger DXSM output function, a 64-bit “cheap multiplier” in the LCG, and outputs from the state before advancing it rather than advance-then-output. PCG64DXSM provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. Supports the method advance to advance the RNG an arbitrary number of steps. The state of the PCG-64 DXSM RNG is represented by 2 128-bit unsigned integers. State and Seeding The PCG64DXSM state vector consists of 2 unsigned 128-bit values, which are represented externally as Python ints. One is the state of the PRNG, which is advanced by a linear congruential generator (LCG). The second is a fixed odd increment used in the LCG. The input seed is processed by SeedSequence to generate both values. The increment is not independently settable. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, PCG64DXSM, SeedSequence >>> sg = SeedSequence(1234) >>> rg = [Generator(PCG64DXSM(s)) for s in sg.spawn(10)] Compatibility Guarantee PCG64DXSM makes a guarantee that a fixed seed will always produce the same random integer stream. References 1 “PCG, A Family of Better Random Number Generators” 2 O’Neill, Melissa E. “PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation” State state Get or set the PRNG state Parallel generation advance(delta) Advance the underlying RNG as-if delta draws have occurred. jumped([jumps]) Returns a new bit generator with the state jumped. Extending cffi CFFI interface ctypes ctypes interface
numpy.reference.random.bit_generators.pcg64dxsm
Philox Counter-based RNG class numpy.random.Philox(seed=None, counter=None, key=None) Container for the Philox (4x64) pseudo-random number generator. Parameters seed{None, int, array_like[ints], SeedSequence}, optional A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. counter{None, int, array_like}, optional Counter to use in the Philox state. Can be either a Python int (long in 2.x) in [0, 2**256) or a 4-element uint64 array. If not provided, the RNG is initialized at 0. key{None, int, array_like}, optional Key to use in the Philox state. Unlike seed, the value in key is directly set. Can be either a Python int in [0, 2**128) or a 2-element uint64 array. key and seed cannot both be used. Notes Philox is a 64-bit PRNG that uses a counter-based design based on weaker (and faster) versions of cryptographic functions [1]. Instances using different values of the key produce independent sequences. Philox has a period of \(2^{256} - 1\) and supports arbitrary advancing and jumping the sequence in increments of \(2^{128}\). These features allow multiple non-overlapping sequences to be generated. Philox provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. State and Seeding The Philox state vector consists of a 256-bit value encoded as a 4-element uint64 array and a 128-bit value encoded as a 2-element uint64 array. The former is a counter which is incremented by 1 for every 4 64-bit randoms produced. The second is a key which determined the sequence produced. Using different keys produces independent sequences. The input seed is processed by SeedSequence to generate the key. The counter is set to 0. Alternately, one can omit the seed parameter and set the key and counter directly. Parallel Features The preferred way to use a BitGenerator in parallel applications is to use the SeedSequence.spawn method to obtain entropy values, and to use these to generate new BitGenerators: >>> from numpy.random import Generator, Philox, SeedSequence >>> sg = SeedSequence(1234) >>> rg = [Generator(Philox(s)) for s in sg.spawn(10)] Philox can be used in parallel applications by calling the jumped method to advances the state as-if \(2^{128}\) random numbers have been generated. Alternatively, advance can be used to advance the counter for any positive step in [0, 2**256). When using jumped, all generators should be chained to ensure that the segments come from the same sequence. >>> from numpy.random import Generator, Philox >>> bit_generator = Philox(1234) >>> rg = [] >>> for _ in range(10): ... rg.append(Generator(bit_generator)) ... bit_generator = bit_generator.jumped() Alternatively, Philox can be used in parallel applications by using a sequence of distinct keys where each instance uses different key. >>> key = 2**96 + 2**33 + 2**17 + 2**9 >>> rg = [Generator(Philox(key=key+i)) for i in range(10)] Compatibility Guarantee Philox makes a guarantee that a fixed seed will always produce the same random integer stream. References 1 John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, “Parallel Random Numbers: As Easy as 1, 2, 3,” Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011. Examples >>> from numpy.random import Generator, Philox >>> rg = Generator(Philox(1234)) >>> rg.standard_normal() 0.123 # random Attributes lock: threading.Lock Lock instance that is shared so that the same bit git generator can be used in multiple Generators without corrupting the state. Code that generates values from a bit generator should hold the bit generator’s lock. State state Get or set the PRNG state Parallel generation advance(delta) Advance the underlying RNG as-if delta draws have occurred. jumped([jumps]) Returns a new bit generator with the state jumped Extending cffi CFFI interface ctypes ctypes interface
numpy.reference.random.bit_generators.philox
Legacy Random Generation The RandomState provides access to legacy generators. This generator is considered frozen and will have no further improvements. It is guaranteed to produce the same values as the final point release of NumPy v1.16. These all depend on Box-Muller normals or inverse CDF exponentials or gammas. This class should only be used if it is essential to have randoms that are identical to what would have been produced by previous versions of NumPy. RandomState adds additional information to the state which is required when using Box-Muller normals since these are produced in pairs. It is important to use RandomState.get_state, and not the underlying bit generators state, when accessing the state so that these extra values are saved. Although we provide the MT19937 BitGenerator for use independent of RandomState, note that its default seeding uses SeedSequence rather than the legacy seeding algorithm. RandomState will use the legacy seeding algorithm. The methods to use the legacy seeding algorithm are currently private as the main reason to use them is just to implement RandomState. However, one can reset the state of MT19937 using the state of the RandomState: from numpy.random import MT19937 from numpy.random import RandomState rs = RandomState(12345) mt19937 = MT19937() mt19937.state = rs.get_state() rs2 = RandomState(mt19937) # Same output rs.standard_normal() rs2.standard_normal() rs.random() rs2.random() rs.standard_exponential() rs2.standard_exponential() class numpy.random.RandomState(seed=None) Container for the slow Mersenne Twister pseudo-random number generator. Consider using a different BitGenerator with the Generator container instead. RandomState and Generator expose a number of methods for generating random numbers drawn from a variety of probability distributions. In addition to the distribution-specific arguments, each method takes a keyword argument size that defaults to None. If size is None, then a single value is generated and returned. If size is an integer, then a 1-D array filled with generated values is returned. If size is a tuple, then an array with that shape is filled and returned. Compatibility Guarantee A fixed bit generator using a fixed seed and a fixed series of calls to ‘RandomState’ methods using the same parameters will always produce the same results up to roundoff error except when the values were incorrect. RandomState is effectively frozen and will only receive updates that are required by changes in the the internals of Numpy. More substantial changes, including algorithmic improvements, are reserved for Generator. Parameters seed{None, int, array_like, BitGenerator}, optional Random seed used to initialize the pseudo-random number generator or an instantized BitGenerator. If an integer or array, used as a seed for the MT19937 BitGenerator. Values can be any integer between 0 and 2**32 - 1 inclusive, an array (or other sequence) of such integers, or None (the default). If seed is None, then the MT19937 BitGenerator is initialized by reading data from /dev/urandom (or the Windows analogue) if available or seed from the clock otherwise. See also Generator MT19937 numpy.random.BitGenerator Notes The Python stdlib module “random” also contains a Mersenne Twister pseudo-random number generator with a number of methods that are similar to the ones available in RandomState. RandomState, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from. Seeding and State get_state() Return a tuple representing the internal state of the generator. set_state(state) Set the internal state of the generator from a tuple. seed(self[, seed]) Reseed a legacy MT19937 BitGenerator Simple random data rand(d0, d1, ..., dn) Random values in a given shape. randn(d0, d1, ..., dn) Return a sample (or samples) from the "standard normal" distribution. randint(low[, high, size, dtype]) Return random integers from low (inclusive) to high (exclusive). random_integers(low[, high, size]) Random integers of type np.int_ between low and high, inclusive. random_sample([size]) Return random floats in the half-open interval [0.0, 1.0). choice(a[, size, replace, p]) Generates a random sample from a given 1-D array bytes(length) Return random bytes. Permutations shuffle(x) Modify a sequence in-place by shuffling its contents. permutation(x) Randomly permute a sequence, or return a permuted range. Distributions beta(a, b[, size]) Draw samples from a Beta distribution. binomial(n, p[, size]) Draw samples from a binomial distribution. chisquare(df[, size]) Draw samples from a chi-square distribution. dirichlet(alpha[, size]) Draw samples from the Dirichlet distribution. exponential([scale, size]) Draw samples from an exponential distribution. f(dfnum, dfden[, size]) Draw samples from an F distribution. gamma(shape[, scale, size]) Draw samples from a Gamma distribution. geometric(p[, size]) Draw samples from the geometric distribution. gumbel([loc, scale, size]) Draw samples from a Gumbel distribution. hypergeometric(ngood, nbad, nsample[, size]) Draw samples from a Hypergeometric distribution. laplace([loc, scale, size]) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay). logistic([loc, scale, size]) Draw samples from a logistic distribution. lognormal([mean, sigma, size]) Draw samples from a log-normal distribution. logseries(p[, size]) Draw samples from a logarithmic series distribution. multinomial(n, pvals[, size]) Draw samples from a multinomial distribution. multivariate_normal(mean, cov[, size, ...]) Draw random samples from a multivariate normal distribution. negative_binomial(n, p[, size]) Draw samples from a negative binomial distribution. noncentral_chisquare(df, nonc[, size]) Draw samples from a noncentral chi-square distribution. noncentral_f(dfnum, dfden, nonc[, size]) Draw samples from the noncentral F distribution. normal([loc, scale, size]) Draw random samples from a normal (Gaussian) distribution. pareto(a[, size]) Draw samples from a Pareto II or Lomax distribution with specified shape. poisson([lam, size]) Draw samples from a Poisson distribution. power(a[, size]) Draws samples in [0, 1] from a power distribution with positive exponent a - 1. rayleigh([scale, size]) Draw samples from a Rayleigh distribution. standard_cauchy([size]) Draw samples from a standard Cauchy distribution with mode = 0. standard_exponential([size]) Draw samples from the standard exponential distribution. standard_gamma(shape[, size]) Draw samples from a standard Gamma distribution. standard_normal([size]) Draw samples from a standard Normal distribution (mean=0, stdev=1). standard_t(df[, size]) Draw samples from a standard Student's t distribution with df degrees of freedom. triangular(left, mode, right[, size]) Draw samples from the triangular distribution over the interval [left, right]. uniform([low, high, size]) Draw samples from a uniform distribution. vonmises(mu, kappa[, size]) Draw samples from a von Mises distribution. wald(mean, scale[, size]) Draw samples from a Wald, or inverse Gaussian, distribution. weibull(a[, size]) Draw samples from a Weibull distribution. zipf(a[, size]) Draw samples from a Zipf distribution. Functions in numpy.random Many of the RandomState methods above are exported as functions in numpy.random This usage is discouraged, as it is implemented via a global RandomState instance which is not advised on two counts: It uses global state, which means results will change as the code changes It uses a RandomState rather than the more modern Generator. For backward compatible legacy reasons, we cannot change this. See Quick Start. beta(a, b[, size]) Draw samples from a Beta distribution. binomial(n, p[, size]) Draw samples from a binomial distribution. bytes(length) Return random bytes. chisquare(df[, size]) Draw samples from a chi-square distribution. choice(a[, size, replace, p]) Generates a random sample from a given 1-D array dirichlet(alpha[, size]) Draw samples from the Dirichlet distribution. exponential([scale, size]) Draw samples from an exponential distribution. f(dfnum, dfden[, size]) Draw samples from an F distribution. gamma(shape[, scale, size]) Draw samples from a Gamma distribution. geometric(p[, size]) Draw samples from the geometric distribution. get_state() Return a tuple representing the internal state of the generator. gumbel([loc, scale, size]) Draw samples from a Gumbel distribution. hypergeometric(ngood, nbad, nsample[, size]) Draw samples from a Hypergeometric distribution. laplace([loc, scale, size]) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay). logistic([loc, scale, size]) Draw samples from a logistic distribution. lognormal([mean, sigma, size]) Draw samples from a log-normal distribution. logseries(p[, size]) Draw samples from a logarithmic series distribution. multinomial(n, pvals[, size]) Draw samples from a multinomial distribution. multivariate_normal(mean, cov[, size, ...]) Draw random samples from a multivariate normal distribution. negative_binomial(n, p[, size]) Draw samples from a negative binomial distribution. noncentral_chisquare(df, nonc[, size]) Draw samples from a noncentral chi-square distribution. noncentral_f(dfnum, dfden, nonc[, size]) Draw samples from the noncentral F distribution. normal([loc, scale, size]) Draw random samples from a normal (Gaussian) distribution. pareto(a[, size]) Draw samples from a Pareto II or Lomax distribution with specified shape. permutation(x) Randomly permute a sequence, or return a permuted range. poisson([lam, size]) Draw samples from a Poisson distribution. power(a[, size]) Draws samples in [0, 1] from a power distribution with positive exponent a - 1. rand(d0, d1, ..., dn) Random values in a given shape. randint(low[, high, size, dtype]) Return random integers from low (inclusive) to high (exclusive). randn(d0, d1, ..., dn) Return a sample (or samples) from the "standard normal" distribution. random([size]) Return random floats in the half-open interval [0.0, 1.0). random_integers(low[, high, size]) Random integers of type np.int_ between low and high, inclusive. random_sample([size]) Return random floats in the half-open interval [0.0, 1.0). ranf This is an alias of random_sample. rayleigh([scale, size]) Draw samples from a Rayleigh distribution. sample This is an alias of random_sample. seed(self[, seed]) Reseed a legacy MT19937 BitGenerator set_state(state) Set the internal state of the generator from a tuple. shuffle(x) Modify a sequence in-place by shuffling its contents. standard_cauchy([size]) Draw samples from a standard Cauchy distribution with mode = 0. standard_exponential([size]) Draw samples from the standard exponential distribution. standard_gamma(shape[, size]) Draw samples from a standard Gamma distribution. standard_normal([size]) Draw samples from a standard Normal distribution (mean=0, stdev=1). standard_t(df[, size]) Draw samples from a standard Student's t distribution with df degrees of freedom. triangular(left, mode, right[, size]) Draw samples from the triangular distribution over the interval [left, right]. uniform([low, high, size]) Draw samples from a uniform distribution. vonmises(mu, kappa[, size]) Draw samples from a von Mises distribution. wald(mean, scale[, size]) Draw samples from a Wald, or inverse Gaussian, distribution. weibull(a[, size]) Draw samples from a Weibull distribution. zipf(a[, size]) Draw samples from a Zipf distribution.
numpy.reference.random.legacy
numpy.random.SeedSequence class numpy.random.SeedSequence(entropy=None, *, spawn_key=(), pool_size=4) SeedSequence mixes sources of entropy in a reproducible way to set the initial state for independent and very probably non-overlapping BitGenerators. Once the SeedSequence is instantiated, you can call the generate_state method to get an appropriately sized seed. Calling spawn(n) will create n SeedSequences that can be used to seed independent BitGenerators, i.e. for different threads. Parameters entropy{None, int, sequence[int]}, optional The entropy for creating a SeedSequence. spawn_key{(), sequence[int]}, optional A third source of entropy, used internally when calling SeedSequence.spawn pool_size{int}, optional Size of the pooled entropy to store. Default is 4 to give a 128-bit entropy pool. 8 (for 256 bits) is another reasonable choice if working with larger PRNGs, but there is very little to be gained by selecting another value. n_children_spawned{int}, optional The number of children already spawned. Only pass this if reconstructing a SeedSequence from a serialized form. Notes Best practice for achieving reproducible bit streams is to use the default None for the initial entropy, and then use SeedSequence.entropy to log/pickle the entropy for reproducibility: >>> sq1 = np.random.SeedSequence() >>> sq1.entropy 243799254704924441050048792905230269161 # random >>> sq2 = np.random.SeedSequence(sq1.entropy) >>> np.all(sq1.generate_state(10) == sq2.generate_state(10)) True Attributes entropy n_children_spawned pool pool_size spawn_key state Methods generate_state(n_words[, dtype]) Return the requested number of words for PRNG seeding. spawn(n_children) Spawn a number of child SeedSequence s by extending the spawn_key.
numpy.reference.random.bit_generators.generated.numpy.random.seedsequence
SFC64 Small Fast Chaotic PRNG class numpy.random.SFC64(seed=None) BitGenerator for Chris Doty-Humphrey’s Small Fast Chaotic PRNG. Parameters seed{None, int, array_like[ints], SeedSequence}, optional A seed to initialize the BitGenerator. If None, then fresh, unpredictable entropy will be pulled from the OS. If an int or array_like[ints] is passed, then it will be passed to SeedSequence to derive the initial BitGenerator state. One may also pass in a SeedSequence instance. Notes SFC64 is a 256-bit implementation of Chris Doty-Humphrey’s Small Fast Chaotic PRNG ([1]). SFC64 has a few different cycles that one might be on, depending on the seed; the expected period will be about \(2^{255}\) ([2]). SFC64 incorporates a 64-bit counter which means that the absolute minimum cycle length is \(2^{64}\) and that distinct seeds will not run into each other for at least \(2^{64}\) iterations. SFC64 provides a capsule containing function pointers that produce doubles, and unsigned 32 and 64- bit integers. These are not directly consumable in Python and must be consumed by a Generator or similar object that supports low-level access. State and Seeding The SFC64 state vector consists of 4 unsigned 64-bit values. The last is a 64-bit counter that increments by 1 each iteration. The input seed is processed by SeedSequence to generate the first 3 values, then the SFC64 algorithm is iterated a small number of times to mix. Compatibility Guarantee SFC64 makes a guarantee that a fixed seed will always produce the same random integer stream. References 1 “PractRand” 2 “Random Invertible Mapping Statistics” State state Get or set the PRNG state Extending cffi CFFI interface ctypes ctypes interface
numpy.reference.random.bit_generators.sfc64
numpy.RankWarning exception numpy.RankWarning[source] Issued by polyfit when the Vandermonde matrix is rank deficient. For more information, a way to suppress the warning, and an example of RankWarning being issued, see polyfit.
numpy.reference.generated.numpy.rankwarning
numpy.ravel numpy.ravel(a, order='C')[source] Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed. As of NumPy 1.10, the returned array will have the same type as the input array. (for example, a masked array will be returned for a masked array input) Parameters aarray_like Input array. The elements in a are read in the order specified by order, and packed as a 1-D array. order{‘C’,’F’, ‘A’, ‘K’}, optional The elements of a are read using this index order. ‘C’ means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used. Returns yarray_like y is an array of the same subtype as a, with shape (a.size,). Note that matrices are special cased for backward compatibility, if a is a matrix, then y is a 1-D ndarray. See also ndarray.flat 1-D iterator over an array. ndarray.flatten 1-D array copy of the elements of an array in row-major order. ndarray.reshape Change the shape of an array without changing its data. Notes In row-major, C-style order, in two dimensions, the row index varies the slowest, and the column index the quickest. This can be generalized to multiple dimensions, where row-major order implies that the index along the first axis varies slowest, and the index along the last quickest. The opposite holds for column-major, Fortran-style index ordering. When a view is desired in as many cases as possible, arr.reshape(-1) may be preferable. Examples It is equivalent to reshape(-1, order=order). >>> x = np.array([[1, 2, 3], [4, 5, 6]]) >>> np.ravel(x) array([1, 2, 3, 4, 5, 6]) >>> x.reshape(-1) array([1, 2, 3, 4, 5, 6]) >>> np.ravel(x, order='F') array([1, 4, 2, 5, 3, 6]) When order is ‘A’, it will preserve the array’s ‘C’ or ‘F’ ordering: >>> np.ravel(x.T) array([1, 4, 2, 5, 3, 6]) >>> np.ravel(x.T, order='A') array([1, 2, 3, 4, 5, 6]) When order is ‘K’, it will preserve orderings that are neither ‘C’ nor ‘F’, but won’t reverse axes: >>> a = np.arange(3)[::-1]; a array([2, 1, 0]) >>> a.ravel(order='C') array([2, 1, 0]) >>> a.ravel(order='K') array([2, 1, 0]) >>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2); a array([[[ 0, 2, 4], [ 1, 3, 5]], [[ 6, 8, 10], [ 7, 9, 11]]]) >>> a.ravel(order='C') array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11]) >>> a.ravel(order='K') array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
numpy.reference.generated.numpy.ravel
numpy.ravel_multi_index numpy.ravel_multi_index(multi_index, dims, mode='raise', order='C') Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index. Parameters multi_indextuple of array_like A tuple of integer arrays, one array for each dimension. dimstuple of ints The shape of array into which the indices from multi_index apply. mode{‘raise’, ‘wrap’, ‘clip’}, optional Specifies how out-of-bounds indices are handled. Can specify either one mode or a tuple of modes, one mode per index. ‘raise’ – raise an error (default) ‘wrap’ – wrap around ‘clip’ – clip to the range In ‘clip’ mode, a negative index which would normally wrap will clip to 0 instead. order{‘C’, ‘F’}, optional Determines whether the multi-index should be viewed as indexing in row-major (C-style) or column-major (Fortran-style) order. Returns raveled_indicesndarray An array of indices into the flattened version of an array of dimensions dims. See also unravel_index Notes New in version 1.6.0. Examples >>> arr = np.array([[3,6,6],[4,5,1]]) >>> np.ravel_multi_index(arr, (7,6)) array([22, 41, 37]) >>> np.ravel_multi_index(arr, (7,6), order='F') array([31, 41, 13]) >>> np.ravel_multi_index(arr, (4,6), mode='clip') array([22, 23, 19]) >>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap')) array([12, 13, 13]) >>> np.ravel_multi_index((3,1,4,1), (6,7,8,9)) 1621
numpy.reference.generated.numpy.ravel_multi_index
numpy.real numpy.real(val)[source] Return the real part of the complex argument. Parameters valarray_like Input array. Returns outndarray or scalar The real component of the complex argument. If val is real, the type of val is used for the output. If val has complex elements, the returned type is float. See also real_if_close, imag, angle Examples >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.real array([1., 3., 5.]) >>> a.real = 9 >>> a array([9.+2.j, 9.+4.j, 9.+6.j]) >>> a.real = np.array([9, 8, 7]) >>> a array([9.+2.j, 8.+4.j, 7.+6.j]) >>> np.real(1 + 1j) 1.0
numpy.reference.generated.numpy.real
numpy.real_if_close numpy.real_if_close(a, tol=100)[source] If input is complex with all imaginary parts close to zero, return real parts. “Close to zero” is defined as tol * (machine epsilon of the type for a). Parameters aarray_like Input array. tolfloat Tolerance in machine epsilons for the complex part of the elements in the array. Returns outndarray If a is real, the type of a is used for the output. If a has complex elements, the returned type is float. See also real, imag, angle Notes Machine epsilon varies from machine to machine and between data types but Python floats on most platforms have a machine epsilon equal to 2.2204460492503131e-16. You can use ‘np.finfo(float).eps’ to print out the machine epsilon for floats. Examples >>> np.finfo(float).eps 2.2204460492503131e-16 # may vary >>> np.real_if_close([2.1 + 4e-14j, 5.2 + 3e-15j], tol=1000) array([2.1, 5.2]) >>> np.real_if_close([2.1 + 4e-13j, 5.2 + 3e-15j], tol=1000) array([2.1+4.e-13j, 5.2 + 3e-15j])
numpy.reference.generated.numpy.real_if_close
numpy.recarray class numpy.recarray(shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, order='C')[source] Construct an ndarray that allows field access using attributes. Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is [(x, int), (y, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['x'] and arr['y']. Record arrays allow the fields to be accessed as members of the array, using arr.x and arr.y. Parameters shapetuple Shape of output array. dtypedata-type, optional The desired data-type. By default, the data-type is determined from formats, names, titles, aligned and byteorder. formatslist of data-types, optional A list containing the data-types for the different columns, e.g. ['i4', 'f8', 'i4']. formats does not support the new convention of using types directly, i.e. (int, float, int). Note that formats must be a list, not a tuple. Given that formats is somewhat limited, we recommend specifying dtype instead. namestuple of str, optional The name of each column, e.g. ('x', 'y', 'z'). bufbuffer, optional By default, a new array is created of the given shape and data-type. If buf is specified and is an object exposing the buffer interface, the array will use the memory from the existing buffer. In this case, the offset and strides keywords are available. Returns recrecarray Empty array of the given shape and type. Other Parameters titlestuple of str, optional Aliases for column names. For example, if names were ('x', 'y', 'z') and titles is ('x_coordinate', 'y_coordinate', 'z_coordinate'), then arr['x'] is equivalent to both arr.x and arr.x_coordinate. byteorder{‘<’, ‘>’, ‘=’}, optional Byte-order for all fields. alignedbool, optional Align the fields in memory as the C-compiler would. stridestuple of ints, optional Buffer (buf) is interpreted according to these strides (strides define how many bytes each array element, row, column, etc. occupy in memory). offsetint, optional Start reading buffer (buf) from this offset onwards. order{‘C’, ‘F’}, optional Row-major (C-style) or column-major (Fortran-style) order. See also core.records.fromrecords Construct a record array from data. record fundamental data-type for recarray. format_parser determine a data-type from formats, names, titles. Notes This constructor can be compared to empty: it creates a new record array but does not fill it with data. To create a record array from data, use one of the following methods: Create a standard ndarray and convert it to a record array, using arr.view(np.recarray) Use the buf keyword. Use np.rec.fromrecords. Examples Create an array with two fields, x and y: >>> x = np.array([(1.0, 2), (3.0, 4)], dtype=[('x', '<f8'), ('y', '<i8')]) >>> x array([(1., 2), (3., 4)], dtype=[('x', '<f8'), ('y', '<i8')]) >>> x['x'] array([1., 3.]) View the array as a record array: >>> x = x.view(np.recarray) >>> x.x array([1., 3.]) >>> x.y array([2, 4]) Create a new, empty record array: >>> np.recarray((2,), ... dtype=[('x', int), ('y', float), ('z', int)]) rec.array([(-1073741821, 1.2249118382103472e-301, 24547520), (3471280, 1.2134086255804012e-316, 0)], dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')]) 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 all([axis, out, keepdims, where]) Returns True if all elements evaluate to True. any([axis, out, keepdims, where]) Returns True if any of the elements of a evaluate to True. argmax([axis, out]) Return indices of the maximum values along the given axis. argmin([axis, out]) Return indices of the minimum values along the given axis. argpartition(kth[, axis, kind, order]) Returns the indices that would partition this array. argsort([axis, kind, order]) Returns the indices that would sort this array. astype(dtype[, order, casting, subok, copy]) Copy of the array, cast to a specified type. byteswap([inplace]) Swap the bytes of the array elements choose(choices[, out, mode]) Use an index array to construct a new array from a set of choices. clip([min, max, out]) Return an array whose values are limited to [min, max]. compress(condition[, axis, out]) Return selected slices of this array along given axis. conj() Complex-conjugate all elements. conjugate() Return the complex conjugate, element-wise. copy([order]) Return a copy of the array. cumprod([axis, dtype, out]) Return the cumulative product of the elements along the given axis. cumsum([axis, dtype, out]) Return the cumulative sum of the elements along the given axis. diagonal([offset, axis1, axis2]) Return specified diagonals. dump(file) Dump a pickle of the array to the specified file. dumps() Returns the pickle of the array as a string. fill(value) Fill the array with a scalar value. 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. item(*args) Copy an element of an array to a standard Python scalar and return it. itemset(*args) Insert scalar into an array (scalar is cast to array's dtype, if possible) max([axis, out, keepdims, initial, where]) Return the maximum along a given axis. mean([axis, dtype, out, keepdims, where]) Returns the average of the array elements along given axis. min([axis, out, keepdims, initial, where]) Return the minimum along a given axis. newbyteorder([new_order]) Return the array with the same data viewed with a different byte order. nonzero() Return the indices of the elements that are non-zero. partition(kth[, axis, kind, order]) Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array. prod([axis, dtype, out, keepdims, initial, ...]) Return the product of the array elements over the given axis ptp([axis, out, keepdims]) Peak to peak (maximum - minimum) value along a given axis. 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. 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. round([decimals, out]) Return a with each element rounded to the given number of decimals. 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. squeeze([axis]) Remove axes of length one from a. std([axis, dtype, out, ddof, keepdims, where]) Returns the standard deviation of the array elements along given axis. sum([axis, dtype, out, keepdims, initial, where]) Return the sum of the array elements over the given axis. swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged. take(indices[, axis, out, mode]) Return an array formed from the elements of a at the given indices. tobytes([order]) Construct Python bytes containing the raw data bytes in the array. 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. trace([offset, axis1, axis2, dtype, out]) Return the sum along diagonals of the array. transpose(*axes) Returns a view of the array with axes transposed. var([axis, dtype, out, ddof, keepdims, where]) Returns the variance of the array elements, along given axis. view([dtype][, type]) New view of array with the same data. dot field
numpy.reference.generated.numpy.recarray
numpy.reciprocal numpy.reciprocal(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'reciprocal'> Return the reciprocal of the argument, element-wise. Calculates 1/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 yndarray Return array. This is a scalar if x is a scalar. Notes Note This function is not designed to work with integers. For integer arguments with absolute value larger than 1 the result is always zero because of the way Python handles integer division. For integer zero the result is an overflow. Examples >>> np.reciprocal(2.) 0.5 >>> np.reciprocal([1, 2., 3.33]) array([ 1. , 0.5 , 0.3003003])
numpy.reference.generated.numpy.reciprocal
numpy.record class numpy.record[source] A data-type scalar that allows field access as attribute lookup. Attributes T Scalar attribute identical to the corresponding array attribute. base base object data Pointer to start of data. dtype dtype object flags integer value of flags flat A 1-D view of the scalar. imag The imaginary part of the scalar. itemsize The length of one element in bytes. nbytes The length of the scalar in bytes. ndim The number of array dimensions. real The real part of the scalar. shape Tuple of array dimensions. size The number of elements in the gentype. strides Tuple of bytes steps in each dimension. Methods all Scalar method identical to the corresponding array attribute. any Scalar method identical to the corresponding array attribute. argmax Scalar method identical to the corresponding array attribute. argmin Scalar method identical to the corresponding array attribute. argsort Scalar method identical to the corresponding array attribute. astype Scalar method identical to the corresponding array attribute. byteswap Scalar method identical to the corresponding array attribute. choose Scalar method identical to the corresponding array attribute. clip Scalar method identical to the corresponding array attribute. compress Scalar method identical to the corresponding array attribute. conjugate Scalar method identical to the corresponding array attribute. copy Scalar method identical to the corresponding array attribute. cumprod Scalar method identical to the corresponding array attribute. cumsum Scalar method identical to the corresponding array attribute. diagonal Scalar method identical to the corresponding array attribute. dump Scalar method identical to the corresponding array attribute. dumps Scalar method identical to the corresponding array attribute. fill Scalar method identical to the corresponding array attribute. flatten Scalar method identical to the corresponding array attribute. getfield Scalar method identical to the corresponding array attribute. item Scalar method identical to the corresponding array attribute. itemset Scalar method identical to the corresponding array attribute. max Scalar method identical to the corresponding array attribute. mean Scalar method identical to the corresponding array attribute. min Scalar method identical to the corresponding array attribute. newbyteorder([new_order]) Return a new dtype with a different byte order. nonzero Scalar method identical to the corresponding array attribute. pprint() Pretty-print all fields. prod Scalar method identical to the corresponding array attribute. ptp Scalar method identical to the corresponding array attribute. put Scalar method identical to the corresponding array attribute. ravel Scalar method identical to the corresponding array attribute. repeat Scalar method identical to the corresponding array attribute. reshape Scalar method identical to the corresponding array attribute. resize Scalar method identical to the corresponding array attribute. round Scalar method identical to the corresponding array attribute. searchsorted Scalar method identical to the corresponding array attribute. setfield Scalar method identical to the corresponding array attribute. setflags Scalar method identical to the corresponding array attribute. sort Scalar method identical to the corresponding array attribute. squeeze Scalar method identical to the corresponding array attribute. std Scalar method identical to the corresponding array attribute. sum Scalar method identical to the corresponding array attribute. swapaxes Scalar method identical to the corresponding array attribute. take Scalar method identical to the corresponding array attribute. tofile Scalar method identical to the corresponding array attribute. tolist Scalar method identical to the corresponding array attribute. tostring Scalar method identical to the corresponding array attribute. trace Scalar method identical to the corresponding array attribute. transpose Scalar method identical to the corresponding array attribute. var Scalar method identical to the corresponding array attribute. view Scalar method identical to the corresponding array attribute. conj tobytes
numpy.reference.generated.numpy.record
numpy.remainder numpy.remainder(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'remainder'> Returns the element-wise remainder of division. Computes the remainder complementary to the floor_divide function. It is equivalent to the Python modulus operator``x1 % x2`` and has the same sign as the divisor x2. The MATLAB function equivalent to np.remainder is mod. Warning This should not be confused with: Python 3.7’s math.remainder and C’s remainder, which computes the IEEE remainder, which are the complement to round(x1 / x2). The MATLAB rem function and or the C % operator which is the complement to int(x1 / x2). Parameters x1array_like Dividend array. x2array_like Divisor array. 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 yndarray The element-wise remainder of the quotient floor_divide(x1, x2). This is a scalar if both x1 and x2 are scalars. See also floor_divide Equivalent of Python // operator. divmod Simultaneous floor division and remainder. fmod Equivalent of the MATLAB rem function. divide, floor Notes Returns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers. mod is an alias of remainder. Examples >>> np.remainder([4, 7], [2, 3]) array([0, 1]) >>> np.remainder(np.arange(7), 5) array([0, 1, 2, 3, 4, 0, 1]) The % operator can be used as a shorthand for np.remainder on ndarrays. >>> x1 = np.arange(7) >>> x1 % 5 array([0, 1, 2, 3, 4, 0, 1])
numpy.reference.generated.numpy.remainder
numpy.repeat numpy.repeat(a, repeats, axis=None)[source] Repeat elements of an array. Parameters aarray_like Input array. repeatsint or array of ints The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis. axisint, optional The axis along which to repeat values. By default, use the flattened input array, and return a flat output array. Returns repeated_arrayndarray Output array which has the same shape as a, except along the given axis. See also tile Tile an array. unique Find the unique elements of an array. Examples >>> np.repeat(3, 4) array([3, 3, 3, 3]) >>> x = np.array([[1,2],[3,4]]) >>> np.repeat(x, 2) array([1, 1, 2, 2, 3, 3, 4, 4]) >>> np.repeat(x, 3, axis=1) array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]) >>> np.repeat(x, [1, 2], axis=0) array([[1, 2], [3, 4], [3, 4]])
numpy.reference.generated.numpy.repeat
numpy.require numpy.require(a, dtype=None, requirements=None, *, like=None)[source] Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes). Parameters aarray_like The object to be converted to a type-and-requirement-satisfying array. dtypedata-type The required data-type. If None preserve the current dtype. If your application requires the data to be in native byteorder, include a byteorder specification as a part of the dtype specification. requirementsstr or list of str The requirements list can be any of the following ‘F_CONTIGUOUS’ (‘F’) - ensure a Fortran-contiguous array ‘C_CONTIGUOUS’ (‘C’) - ensure a C-contiguous array ‘ALIGNED’ (‘A’) - ensure a data-type aligned array ‘WRITEABLE’ (‘W’) - ensure a writable array ‘OWNDATA’ (‘O’) - ensure an array that owns its own data ‘ENSUREARRAY’, (‘E’) - ensure a base array, instead of a subclass likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns outndarray Array with specified requirements and type if given. See also asarray Convert input to an ndarray. asanyarray Convert to an ndarray, but pass through ndarray subclasses. ascontiguousarray Convert input to a contiguous array. asfortranarray Convert input to an ndarray with column-major memory order. ndarray.flags Information about the memory layout of the array. Notes The returned array will be guaranteed to have the listed requirements by making a copy if needed. Examples >>> x = np.arange(6).reshape(2,3) >>> x.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False >>> y = np.require(x, dtype=np.float32, requirements=['A', 'O', 'W', 'F']) >>> y.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True WRITEBACKIFCOPY : False UPDATEIFCOPY : False
numpy.reference.generated.numpy.require
numpy.reshape numpy.reshape(a, newshape, order='C')[source] Gives a new shape to an array without changing its data. Parameters aarray_like Array to be reshaped. newshapeint or tuple of ints The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. order{‘C’, ‘F’, ‘A’}, optional Read the elements of a using this index order, and place the elements into the reshaped array using this index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of indexing. ‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. Returns reshaped_arrayndarray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array. See also ndarray.reshape Equivalent method. Notes It is not always possible to change the shape of an array without copying the data. If you want an error to be raised when the data is copied, you should assign the new shape to the shape attribute of the array: >>> a = np.zeros((10, 2)) # A transpose makes the array non-contiguous >>> b = a.T # Taking a view makes it possible to modify the shape without modifying # the initial object. >>> c = b.view() >>> c.shape = (20) Traceback (most recent call last): ... AttributeError: Incompatible shape for in-place modification. Use `.reshape()` to make a copy with the desired shape. The order keyword gives the index ordering both for fetching the values from a, and then placing the values into the output array. For example, let’s say you have an array: >>> a = np.arange(6).reshape((3, 2)) >>> a array([[0, 1], [2, 3], [4, 5]]) You can think of reshaping as first raveling the array (using the given index order), then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling. >>> np.reshape(a, (2, 3)) # C-like index ordering array([[0, 1, 2], [3, 4, 5]]) >>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape array([[0, 1, 2], [3, 4, 5]]) >>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering array([[0, 4, 3], [2, 1, 5]]) >>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F') array([[0, 4, 3], [2, 1, 5]]) Examples >>> a = np.array([[1,2,3], [4,5,6]]) >>> np.reshape(a, 6) array([1, 2, 3, 4, 5, 6]) >>> np.reshape(a, 6, order='F') array([1, 4, 2, 5, 3, 6]) >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 array([[1, 2], [3, 4], [5, 6]])
numpy.reference.generated.numpy.reshape
numpy.resize numpy.resize(a, new_shape)[source] Return a new array with the specified shape. If the new array is larger than the original array, then the new array is filled with repeated copies of a. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a. Parameters aarray_like Array to be resized. new_shapeint or tuple of int Shape of resized array. Returns reshaped_arrayndarray The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order. See also numpy.reshape Reshape an array without changing the total size. numpy.pad Enlarge and pad an array. numpy.repeat Repeat elements of an array. ndarray.resize resize an array in-place. Notes When the total size of the array does not change reshape should be used. In most other cases either indexing (to reduce the size) or padding (to increase the size) may be a more appropriate solution. Warning: This functionality does not consider axes separately, i.e. it does not apply interpolation/extrapolation. It fills the return array with the required number of elements, iterating over a in C-order, disregarding axes (and cycling back from the start if the new shape is larger). This functionality is therefore not suitable to resize images, or data where each axis represents a separate and distinct entity. Examples >>> a=np.array([[0,1],[2,3]]) >>> np.resize(a,(2,3)) array([[0, 1, 2], [3, 0, 1]]) >>> np.resize(a,(1,4)) array([[0, 1, 2, 3]]) >>> np.resize(a,(2,4)) array([[0, 1, 2, 3], [0, 1, 2, 3]])
numpy.reference.generated.numpy.resize
numpy.result_type numpy.result_type(*arrays_and_dtypes) Returns the type that results from applying the NumPy type promotion rules to the arguments. Type promotion in NumPy works similarly to the rules in languages like C++, with some slight differences. When both scalars and arrays are used, the array’s type takes precedence and the actual value of the scalar is taken into account. For example, calculating 3*a, where a is an array of 32-bit floats, intuitively should result in a 32-bit float output. If the 3 is a 32-bit integer, the NumPy rules indicate it can’t convert losslessly into a 32-bit float, so a 64-bit float should be the result type. By examining the value of the constant, ‘3’, we see that it fits in an 8-bit integer, which can be cast losslessly into the 32-bit float. Parameters arrays_and_dtypeslist of arrays and dtypes The operands of some operation whose result type is needed. Returns outdtype The result type. See also dtype, promote_types, min_scalar_type, can_cast Notes New in version 1.6.0. The specific algorithm used is as follows. Categories are determined by first checking which of boolean, integer (int/uint), or floating point (float/complex) the maximum kind of all the arrays and the scalars are. If there are only scalars or the maximum category of the scalars is higher than the maximum category of the arrays, the data types are combined with promote_types to produce the return value. Otherwise, min_scalar_type is called on each array, and the resulting data types are all combined with promote_types to produce the return value. The set of int values is not a subset of the uint values for types with the same number of bits, something not reflected in min_scalar_type, but handled as a special case in result_type. Examples >>> np.result_type(3, np.arange(7, dtype='i1')) dtype('int8') >>> np.result_type('i4', 'c8') dtype('complex128') >>> np.result_type(3.0, -2) dtype('float64')
numpy.reference.generated.numpy.result_type
numpy.right_shift numpy.right_shift(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'right_shift'> Shift the bits of an integer to the right. Bits are shifted to the right x2. Because the internal representation of numbers is in binary format, this operation is equivalent to dividing x1 by 2**x2. Parameters x1array_like, int Input values. x2array_like, int Number of bits to remove at the right of 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, int Return x1 with bits shifted x2 times to the right. This is a scalar if both x1 and x2 are scalars. See also left_shift Shift the bits of an integer to the left. binary_repr Return the binary representation of the input number as a string. Examples >>> np.binary_repr(10) '1010' >>> np.right_shift(10, 1) 5 >>> np.binary_repr(5) '101' >>> np.right_shift(10, [1,2,3]) array([5, 2, 1]) The >> operator can be used as a shorthand for np.right_shift on ndarrays. >>> x1 = 10 >>> x2 = np.array([1,2,3]) >>> x1 >> x2 array([5, 2, 1])
numpy.reference.generated.numpy.right_shift
numpy.rint numpy.rint(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'rint'> Round elements of the array to the nearest integer. 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 is same shape and type as x. This is a scalar if x is a scalar. See also fix, ceil, floor, trunc Notes For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.rint(a) array([-2., -2., -0., 0., 2., 2., 2.])
numpy.reference.generated.numpy.rint
numpy.roll numpy.roll(a, shift, axis=None)[source] Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first. Parameters aarray_like Input array. shiftint or tuple of ints The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while axis is a tuple of ints, then the same value is used for all given axes. axisint or tuple of ints, optional Axis or axes along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored. Returns resndarray Output array, with the same shape as a. See also rollaxis Roll the specified axis backwards, until it lies in a given position. Notes New in version 1.12.0. Supports rolling over multiple dimensions simultaneously. Examples >>> x = np.arange(10) >>> np.roll(x, 2) array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]) >>> np.roll(x, -2) array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]) >>> x2 = np.reshape(x, (2, 5)) >>> x2 array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> np.roll(x2, 1) array([[9, 0, 1, 2, 3], [4, 5, 6, 7, 8]]) >>> np.roll(x2, -1) array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 0]]) >>> np.roll(x2, 1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, -1, axis=0) array([[5, 6, 7, 8, 9], [0, 1, 2, 3, 4]]) >>> np.roll(x2, 1, axis=1) array([[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]) >>> np.roll(x2, -1, axis=1) array([[1, 2, 3, 4, 0], [6, 7, 8, 9, 5]]) >>> np.roll(x2, (1, 1), axis=(1, 0)) array([[9, 5, 6, 7, 8], [4, 0, 1, 2, 3]]) >>> np.roll(x2, (2, 1), axis=(1, 0)) array([[8, 9, 5, 6, 7], [3, 4, 0, 1, 2]])
numpy.reference.generated.numpy.roll
numpy.rollaxis numpy.rollaxis(a, axis, start=0)[source] Roll the specified axis backwards, until it lies in a given position. This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11. Parameters andarray Input array. axisint The axis to be rolled. The positions of the other axes do not change relative to one another. startint, optional When start <= axis, the axis is rolled back until it lies in this position. When start > axis, the axis is rolled until it lies before this position. The default, 0, results in a “complete” roll. The following table describes how negative values of start are interpreted: start Normalized start -(arr.ndim+1) raise AxisError -arr.ndim 0 ⋮ ⋮ -1 arr.ndim-1 0 0 ⋮ ⋮ arr.ndim arr.ndim arr.ndim + 1 raise AxisError Returns resndarray For NumPy >= 1.10.0 a view of a is always returned. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned. See also moveaxis Move array axes to new positions. roll Roll the elements of an array by a number of positions along a given axis. Examples >>> a = np.ones((3,4,5,6)) >>> np.rollaxis(a, 3, 1).shape (3, 6, 4, 5) >>> np.rollaxis(a, 2).shape (5, 3, 4, 6) >>> np.rollaxis(a, 1, 4).shape (3, 5, 6, 4)
numpy.reference.generated.numpy.rollaxis
numpy.roots numpy.roots(p)[source] Return the roots of a polynomial with coefficients given in p. Note This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in numpy.polynomial is preferred. A summary of the differences can be found in the transition guide. The values in the rank-1 array p are coefficients of a polynomial. If the length of p is n+1 then the polynomial is described by: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters parray_like Rank-1 array of polynomial coefficients. Returns outndarray An array containing the roots of the polynomial. Raises ValueError When p cannot be converted to a rank-1 array. See also poly Find the coefficients of a polynomial with a given sequence of roots. polyval Compute polynomial values. polyfit Least squares polynomial fit. poly1d A one-dimensional polynomial class. Notes The algorithm relies on computing the eigenvalues of the companion matrix [1]. References 1 R. A. Horn & C. R. Johnson, Matrix Analysis. Cambridge, UK: Cambridge University Press, 1999, pp. 146-7. Examples >>> coeff = [3.2, 2, 1] >>> np.roots(coeff) array([-0.3125+0.46351241j, -0.3125-0.46351241j])
numpy.reference.generated.numpy.roots
numpy.rot90 numpy.rot90(m, k=1, axes=(0, 1))[source] Rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. Parameters marray_like Array of two or more dimensions. kinteger Number of times the array is rotated by 90 degrees. axes: (2,) array_like The array is rotated in the plane defined by the axes. Axes must be different. New in version 1.12.0. Returns yndarray A rotated view of m. See also flip Reverse the order of elements in an array along the given axis. fliplr Flip an array horizontally. flipud Flip an array vertically. Notes rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1)) rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1)) Examples >>> m = np.array([[1,2],[3,4]], int) >>> m array([[1, 2], [3, 4]]) >>> np.rot90(m) array([[2, 4], [1, 3]]) >>> np.rot90(m, 2) array([[4, 3], [2, 1]]) >>> m = np.arange(8).reshape((2,2,2)) >>> np.rot90(m, 1, (1,2)) array([[[1, 3], [0, 2]], [[5, 7], [4, 6]]])
numpy.reference.generated.numpy.rot90
numpy.round_ numpy.round_(a, decimals=0, out=None)[source] Round an array to the given number of decimals. See also around equivalent function; see for details.
numpy.reference.generated.numpy.round_
numpy.row_stack numpy.row_stack(tup)[source] Stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. This function makes most sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r/g/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters tupsequence of ndarrays The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length. Returns stackedndarray The array formed by stacking the given arrays, will be at least 2-D. See also concatenate Join a sequence of arrays along an existing axis. stack Join a sequence of arrays along a new axis. block Assemble an nd-array from nested lists of blocks. 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). Examples >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.vstack((a,b)) array([[1, 2, 3], [4, 5, 6]]) >>> a = np.array([[1], [2], [3]]) >>> b = np.array([[4], [5], [6]]) >>> np.vstack((a,b)) array([[1], [2], [3], [4], [5], [6]])
numpy.reference.generated.numpy.row_stack
numpy.s_ numpy.s_ = <numpy.lib.index_tricks.IndexExpression object> A nicer way to build up index tuples for arrays. Note Use one of the two predefined instances index_exp or s_ rather than directly using IndexExpression. For any index combination, including slicing and axis insertion, a[indices] is the same as a[np.index_exp[indices]] for any array a. However, np.index_exp[indices] can be used anywhere in Python code and returns a tuple of slice objects that can be used in the construction of complex index expressions. Parameters maketuplebool If True, always returns a tuple. See also index_exp Predefined instance that always returns a tuple: index_exp = IndexExpression(maketuple=True). s_ Predefined instance without tuple conversion: s_ = IndexExpression(maketuple=False). Notes You can do all this with slice() plus a few special objects, but there’s a lot to remember and this version is simpler because it uses the standard array indexing syntax. Examples >>> np.s_[2::2] slice(2, None, 2) >>> np.index_exp[2::2] (slice(2, None, 2),) >>> np.array([0, 1, 2, 3, 4])[np.s_[2::2]] array([2, 4])
numpy.reference.generated.numpy.s_
numpy.save numpy.save(file, arr, allow_pickle=True, fix_imports=True)[source] Save an array to a binary file in NumPy .npy format. Parameters filefile, str, or pathlib.Path File or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one. arrarray_like Array data to be saved. allow_picklebool, optional Allow saving object arrays using Python pickles. Reasons for disallowing pickles include security (loading pickled data can execute arbitrary code) and portability (pickled objects may not be loadable on different Python installations, for example if the stored objects require libraries that are not available, and not all pickled data is compatible between Python 2 and Python 3). Default: True fix_importsbool, optional Only useful in forcing objects in object arrays on Python 3 to be pickled in a Python 2 compatible way. If fix_imports is True, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. See also savez Save several arrays into a .npz archive savetxt, load Notes For a description of the .npy format, see numpy.lib.format. Any data saved to the file is appended to the end of the file. Examples >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> np.save(outfile, x) >>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file >>> np.load(outfile) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> with open('test.npy', 'wb') as f: ... np.save(f, np.array([1, 2])) ... np.save(f, np.array([1, 3])) >>> with open('test.npy', 'rb') as f: ... a = np.load(f) ... b = np.load(f) >>> print(a, b) # [1 2] [1 3]
numpy.reference.generated.numpy.save
numpy.savetxt numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)[source] Save an array to a text file. Parameters fnamefilename or file handle If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently. X1D or 2D array_like Data to be saved to a text file. fmtstr or sequence of strs, optional A single format (%10.5f), a sequence of formats, or a multi-format string, e.g. ‘Iteration %d – %10.5f’, in which case delimiter is ignored. For complex X, the legal options for fmt are: a single specifier, fmt=’%.4e’, resulting in numbers formatted like ‘ (%s+%sj)’ % (fmt, fmt) a full string specifying every real and imaginary part, e.g. ‘ %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej’ for 3 columns a list of specifiers, one per column - in this case, the real and imaginary part must have separate specifiers, e.g. [‘%.3e + %.3ej’, ‘(%.15e%+.15ej)’] for 2 columns delimiterstr, optional String or character separating columns. newlinestr, optional String or character separating lines. New in version 1.5.0. headerstr, optional String that will be written at the beginning of the file. New in version 1.7.0. footerstr, optional String that will be written at the end of the file. New in version 1.7.0. commentsstr, optional String that will be prepended to the header and footer strings, to mark them as comments. Default: ‘# ‘, as expected by e.g. numpy.loadtxt. New in version 1.7.0. encoding{None, str}, optional Encoding used to encode the outputfile. Does not apply to output streams. If the encoding is something other than ‘bytes’ or ‘latin1’ you will not be able to load the file in NumPy versions < 1.14. Default is ‘latin1’. New in version 1.14.0. See also save Save an array to a binary file in NumPy .npy format savez Save several arrays into an uncompressed .npz archive savez_compressed Save several arrays into a compressed .npz archive Notes Further explanation of the fmt parameter (%[flag]width[.precision]specifier): flags: - : left justify + : Forces to precede result with + or -. 0 : Left pad the number with zeros instead of space (see width). width: Minimum number of characters to be printed. The value is not truncated if it has more characters. precision: For integer specifiers (eg. d,i,o,x), the minimum number of digits. For e, E and f specifiers, the number of digits to print after the decimal point. For g and G, the maximum number of significant digits. For s, the maximum number of characters. specifiers: c : character d or i : signed decimal integer e or E : scientific notation with e or E. f : decimal floating point g,G : use the shorter of e,E or f o : signed octal s : string of characters u : unsigned decimal integer x,X : unsigned hexadecimal integer This explanation of fmt is not complete, for an exhaustive specification see [1]. References 1 Format Specification Mini-Language, Python Documentation. Examples >>> x = y = z = np.arange(0.0,5.0,1.0) >>> np.savetxt('test.out', x, delimiter=',') # X is an array >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation
numpy.reference.generated.numpy.savetxt
numpy.savez numpy.savez(file, *args, **kwds)[source] Save several arrays into a single file in uncompressed .npz format. Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y). If arrays are specified as positional arguments, i.e., savez(fn, x, y), their names will be arr_0, arr_1, etc. Parameters filestr or file Either the filename (string) or an open file (file-like object) where the data will be saved. If file is a string or a Path, the .npz extension will be appended to the filename if it is not already there. argsArguments, optional Arrays to save to the file. Please use keyword arguments (see kwds below) to assign names to arrays. Arrays specified as args will be named “arr_0”, “arr_1”, and so on. kwdsKeyword arguments, optional Arrays to save to the file. Each array will be saved to the output file with its corresponding keyword name. Returns None See also save Save a single array to a binary file in NumPy format. savetxt Save an array to a file as plain text. savez_compressed Save several arrays into a compressed .npz archive Notes The .npz file format is a zipped archive of files named after the variables they contain. The archive is not compressed and each file in the archive contains one variable in .npy format. For a description of the .npy format, see numpy.lib.format. When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves. Keys passed in kwds are used as filenames inside the ZIP archive. Therefore, keys should be valid filenames; e.g., avoid keys that begin with / or contain .. When naming variables with keyword arguments, it is not possible to name a variable file, as this would cause the file argument to be defined twice in the call to savez. Examples >>> from tempfile import TemporaryFile >>> outfile = TemporaryFile() >>> x = np.arange(10) >>> y = np.sin(x) Using savez with *args, the arrays are saved with default names. >>> np.savez(outfile, x, y) >>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file >>> npzfile = np.load(outfile) >>> npzfile.files ['arr_0', 'arr_1'] >>> npzfile['arr_0'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Using savez with **kwds, the arrays are saved with the keyword names. >>> outfile = TemporaryFile() >>> np.savez(outfile, x=x, y=y) >>> _ = outfile.seek(0) >>> npzfile = np.load(outfile) >>> sorted(npzfile.files) ['x', 'y'] >>> npzfile['x'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
numpy.reference.generated.numpy.savez
numpy.savez_compressed numpy.savez_compressed(file, *args, **kwds)[source] Save several arrays into a single file in compressed .npz format. Provide arrays as keyword arguments to store them under the corresponding name in the output file: savez(fn, x=x, y=y). If arrays are specified as positional arguments, i.e., savez(fn, x, y), their names will be arr_0, arr_1, etc. Parameters filestr or file Either the filename (string) or an open file (file-like object) where the data will be saved. If file is a string or a Path, the .npz extension will be appended to the filename if it is not already there. argsArguments, optional Arrays to save to the file. Please use keyword arguments (see kwds below) to assign names to arrays. Arrays specified as args will be named “arr_0”, “arr_1”, and so on. kwdsKeyword arguments, optional Arrays to save to the file. Each array will be saved to the output file with its corresponding keyword name. Returns None See also numpy.save Save a single array to a binary file in NumPy format. numpy.savetxt Save an array to a file as plain text. numpy.savez Save several arrays into an uncompressed .npz file format numpy.load Load the files created by savez_compressed. Notes The .npz file format is a zipped archive of files named after the variables they contain. The archive is compressed with zipfile.ZIP_DEFLATED and each file in the archive contains one variable in .npy format. For a description of the .npy format, see numpy.lib.format. When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves. Examples >>> test_array = np.random.rand(3, 2) >>> test_vector = np.random.rand(4) >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector) >>> loaded = np.load('/tmp/123.npz') >>> print(np.array_equal(test_array, loaded['a'])) True >>> print(np.array_equal(test_vector, loaded['b'])) True
numpy.reference.generated.numpy.savez_compressed
numpy.sctype2char numpy.sctype2char(sctype)[source] Return the string representation of a scalar dtype. Parameters sctypescalar dtype or object If a scalar dtype, the corresponding string character is returned. If an object, sctype2char tries to infer its scalar type and then return the corresponding string character. Returns typecharstr The string character corresponding to the scalar type. Raises ValueError If sctype is an object for which the type can not be inferred. See also obj2sctype, issctype, issubsctype, mintypecode Examples >>> for sctype in [np.int32, np.double, np.complex_, np.string_, np.ndarray]: ... print(np.sctype2char(sctype)) l # may vary d D S O >>> x = np.array([1., 2-1.j]) >>> np.sctype2char(x) 'D' >>> np.sctype2char(list) 'O'
numpy.reference.generated.numpy.sctype2char
numpy.searchsorted numpy.searchsorted(a, v, side='left', sorter=None)[source] Find indices where elements should be inserted to maintain order. Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved. Assuming that a is sorted: side returned index i satisfies left a[i-1] < v <= a[i] right a[i-1] <= v < a[i] Parameters a1-D array_like Input array. If sorter is None, then it must be sorted in ascending order, otherwise sorter must be an array of indices that sort it. varray_like Values to insert into a. side{‘left’, ‘right’}, optional If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of a). sorter1-D array_like, optional Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort. New in version 1.7.0. Returns indicesint or array of ints Array of insertion points with the same shape as v, or an integer if v is a scalar. See also sort Return a sorted copy of an array. histogram Produce histogram from 1-D data. Notes Binary search is used to find the required insertion points. As of NumPy 1.4.0 searchsorted works with real/complex arrays containing nan values. The enhanced sort order is documented in sort. This function uses the same algorithm as the builtin python bisect.bisect_left (side='left') and bisect.bisect_right (side='right') functions, which is also vectorized in the v argument. Examples >>> np.searchsorted([1,2,3,4,5], 3) 2 >>> np.searchsorted([1,2,3,4,5], 3, side='right') 3 >>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3]) array([0, 5, 1, 2])
numpy.reference.generated.numpy.searchsorted
numpy.select numpy.select(condlist, choicelist, default=0)[source] Return an array drawn from elements in choicelist, depending on conditions. Parameters condlistlist of bool ndarrays The list of conditions which determine from which array in choicelist the output elements are taken. When multiple conditions are satisfied, the first one encountered in condlist is used. choicelistlist of ndarrays The list of arrays from which the output elements are taken. It has to be of the same length as condlist. defaultscalar, optional The element inserted in output when all conditions evaluate to False. Returns outputndarray The output at position m is the m-th element of the array in choicelist where the m-th element of the corresponding array in condlist is True. See also where Return elements from one of two arrays depending on condition. take, choose, compress, diag, diagonal Examples >>> x = np.arange(6) >>> condlist = [x<3, x>3] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist, 42) array([ 0, 1, 2, 42, 16, 25]) >>> condlist = [x<=4, x>3] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist, 55) array([ 0, 1, 2, 3, 4, 25])
numpy.reference.generated.numpy.select
numpy.set_printoptions numpy.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, *, legacy=None)[source] Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed. Parameters precisionint or None, optional Number of digits of precision for floating point output (default 8). May be None if floatmode is not fixed, to print as many digits as necessary to uniquely specify the value. thresholdint, optional Total number of array elements which trigger summarization rather than full repr (default 1000). To always use the full repr without summarization, pass sys.maxsize. edgeitemsint, optional Number of array items in summary at beginning and end of each dimension (default 3). linewidthint, optional The number of characters per line for the purpose of inserting line breaks (default 75). suppressbool, optional If True, always print floating point numbers using fixed point notation, in which case numbers equal to zero in the current precision will print as zero. If False, then scientific notation is used when absolute value of the smallest number is < 1e-4 or the ratio of the maximum absolute value to the minimum is > 1e3. The default is False. nanstrstr, optional String representation of floating point not-a-number (default nan). infstrstr, optional String representation of floating point infinity (default inf). signstring, either ‘-’, ‘+’, or ‘ ‘, optional Controls printing of the sign of floating-point types. If ‘+’, always print the sign of positive values. If ‘ ‘, always prints a space (whitespace character) in the sign position of positive values. If ‘-’, omit the sign character of positive values. (default ‘-‘) formatterdict of callables, optional If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are: ‘bool’ ‘int’ ‘timedelta’ : a numpy.timedelta64 ‘datetime’ : a numpy.datetime64 ‘float’ ‘longfloat’ : 128-bit floats ‘complexfloat’ ‘longcomplexfloat’ : composed of two 128-bit floats ‘numpystr’ : types numpy.string_ and numpy.unicode_ ‘object’ : np.object_ arrays Other keys that can be used to set a group of types at once are: ‘all’ : sets all types ‘int_kind’ : sets ‘int’ ‘float_kind’ : sets ‘float’ and ‘longfloat’ ‘complex_kind’ : sets ‘complexfloat’ and ‘longcomplexfloat’ ‘str_kind’ : sets ‘numpystr’ floatmodestr, optional Controls the interpretation of the precision option for floating-point types. Can take the following values (default maxprec_equal): ‘fixed’: Always print exactly precision fractional digits, even if this would print more or fewer digits than necessary to specify the value uniquely. ‘unique’: Print the minimum number of fractional digits necessary to represent each value uniquely. Different elements may have a different number of digits. The value of the precision option is ignored. ‘maxprec’: Print at most precision fractional digits, but if an element can be uniquely represented with fewer digits only print it with that many. ‘maxprec_equal’: Print at most precision fractional digits, but if every element in the array can be uniquely represented with an equal number of fewer digits, use that many digits for all elements. legacystring or False, optional If set to the string ‘1.13’ enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. This also enables 1.21 legacy printing mode (described below). If set to the string ‘1.21’ enables 1.21 legacy printing mode. This approximates numpy 1.21 print output of complex structured dtypes by not inserting spaces after commas that separate fields and after colons. If set to False, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility. New in version 1.14.0. Changed in version 1.22.0. See also get_printoptions, printoptions, set_string_function, array2string Notes formatter is always reset with a call to set_printoptions. Use printoptions as a context manager to set the values temporarily. Examples Floating point precision can be set: >>> np.set_printoptions(precision=4) >>> np.array([1.123456789]) [1.1235] Long arrays can be summarised: >>> np.set_printoptions(threshold=5) >>> np.arange(10) array([0, 1, 2, ..., 7, 8, 9]) Small results can be suppressed: >>> eps = np.finfo(float).eps >>> x = np.arange(4.) >>> x**2 - (x + eps)**2 array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) >>> np.set_printoptions(suppress=True) >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.]) A custom formatter can be used to display array elements as desired: >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)}) >>> x = np.arange(3) >>> x array([int: 0, int: -1, int: -2]) >>> np.set_printoptions() # formatter gets reset >>> x array([0, 1, 2]) To put back the default options, you can use: >>> np.set_printoptions(edgeitems=3, infstr='inf', ... linewidth=75, nanstr='nan', precision=8, ... suppress=False, threshold=1000, formatter=None) Also to temporarily override options, use printoptions as a context manager: >>> with np.printoptions(precision=2, suppress=True, threshold=5): ... np.linspace(0, 10, 10) array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ])
numpy.reference.generated.numpy.set_printoptions
numpy.set_string_function numpy.set_string_function(f, repr=True)[source] Set a Python function to be used when pretty printing arrays. Parameters ffunction or None Function to be used to pretty print arrays. The function should expect a single array argument and return a string of the representation of the array. If None, the function is reset to the default NumPy function to print arrays. reprbool, optional If True (default), the function for pretty printing (__repr__) is set, if False the function that returns the default string representation (__str__) is set. See also set_printoptions, get_printoptions Examples >>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> np.set_string_function(pprint) >>> a = np.arange(10) >>> a HA! - What are you going to do now? >>> _ = a >>> # [0 1 2 3 4 5 6 7 8 9] We can reset the function to the default: >>> np.set_string_function(None) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) repr affects either pretty printing or normal string representation. Note that __repr__ is still affected by setting __str__ because the width of each array element in the returned string becomes equal to the length of the result of __str__(). >>> x = np.arange(4) >>> np.set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([0, 1, 2, 3])'
numpy.reference.generated.numpy.set_string_function
numpy.setbufsize numpy.setbufsize(size)[source] Set the size of the buffer used in ufuncs. Parameters sizeint Size of buffer.
numpy.reference.generated.numpy.setbufsize
numpy.setdiff1d numpy.setdiff1d(ar1, ar2, assume_unique=False)[source] Find the set difference of two arrays. Return the unique values in ar1 that are not in ar2. Parameters ar1array_like Input array. ar2array_like Input comparison array. assume_uniquebool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns setdiff1dndarray 1D array of values in ar1 that are not in ar2. The result is sorted when assume_unique=False, but otherwise only sorted if the input is sorted. See also numpy.lib.arraysetops Module with a number of other functions for performing set operations on arrays. Examples >>> a = np.array([1, 2, 3, 2, 4, 1]) >>> b = np.array([3, 4, 5, 6]) >>> np.setdiff1d(a, b) array([1, 2])
numpy.reference.generated.numpy.setdiff1d
numpy.seterr numpy.seterr(all=None, divide=None, over=None, under=None, invalid=None)[source] Set how floating-point errors are handled. Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by these settings. Parameters all{‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}, optional Set treatment for all types of floating-point errors at once: ignore: Take no action when the exception occurs. warn: Print a RuntimeWarning (via the Python warnings module). raise: Raise a FloatingPointError. call: Call a function specified using the seterrcall function. print: Print a warning directly to stdout. log: Record error in a Log object specified by seterrcall. The default is not to change the current behavior. divide{‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}, optional Treatment for division by zero. over{‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}, optional Treatment for floating-point overflow. under{‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}, optional Treatment for floating-point underflow. invalid{‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}, optional Treatment for invalid floating-point operation. Returns old_settingsdict Dictionary containing the old settings. See also seterrcall Set a callback function for the ‘call’ mode. geterr, geterrcall, errstate Notes The floating-point exceptions are defined in the IEEE 754 standard [1]: Division by zero: infinite result obtained from finite numbers. Overflow: result too large to be expressed. Underflow: result so close to zero that some precision was lost. Invalid operation: result is not an expressible number, typically indicates that a NaN was produced. 1 https://en.wikipedia.org/wiki/IEEE_754 Examples >>> old_settings = np.seterr(all='ignore') #seterr to known value >>> np.seterr(over='raise') {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'} >>> np.seterr(**old_settings) # reset to default {'divide': 'ignore', 'over': 'raise', 'under': 'ignore', 'invalid': 'ignore'} >>> np.int16(32000) * np.int16(3) 30464 >>> old_settings = np.seterr(all='warn', over='raise') >>> np.int16(32000) * np.int16(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> FloatingPointError: overflow encountered in short_scalars >>> old_settings = np.seterr(all='print') >>> np.geterr() {'divide': 'print', 'over': 'print', 'under': 'print', 'invalid': 'print'} >>> np.int16(32000) * np.int16(3) 30464
numpy.reference.generated.numpy.seterr
numpy.seterrcall numpy.seterrcall(func)[source] Set the floating-point error callback function or log object. There are two ways to capture floating-point error messages. The first is to set the error-handler to ‘call’, using seterr. Then, set the function to call using this function. The second is to set the error-handler to ‘log’, using seterr. Floating-point errors then trigger a call to the ‘write’ method of the provided object. Parameters funccallable f(err, flag) or object with write method Function to call upon floating-point errors (‘call’-mode) or object whose ‘write’ method is used to log such message (‘log’-mode). The call function takes two arguments. The first is a string describing the type of error (such as “divide by zero”, “overflow”, “underflow”, or “invalid value”), and the second is the status flag. The flag is a byte, whose four least-significant bits indicate the type of error, one of “divide”, “over”, “under”, “invalid”: [0 0 0 0 divide over under invalid] In other words, flags = divide + 2*over + 4*under + 8*invalid. If an object is provided, its write method should take one argument, a string. Returns hcallable, log instance or None The old error handler. See also seterr, geterr, geterrcall Examples Callback upon error: >>> def err_handler(type, flag): ... print("Floating point error (%s), with flag %s" % (type, flag)) ... >>> saved_handler = np.seterrcall(err_handler) >>> save_err = np.seterr(all='call') >>> np.array([1, 2, 3]) / 0.0 Floating point error (divide by zero), with flag 1 array([inf, inf, inf]) >>> np.seterrcall(saved_handler) <function err_handler at 0x...> >>> np.seterr(**save_err) {'divide': 'call', 'over': 'call', 'under': 'call', 'invalid': 'call'} Log error message: >>> class Log: ... def write(self, msg): ... print("LOG: %s" % msg) ... >>> log = Log() >>> saved_handler = np.seterrcall(log) >>> save_err = np.seterr(all='log') >>> np.array([1, 2, 3]) / 0.0 LOG: Warning: divide by zero encountered in true_divide array([inf, inf, inf]) >>> np.seterrcall(saved_handler) <numpy.core.numeric.Log object at 0x...> >>> np.seterr(**save_err) {'divide': 'log', 'over': 'log', 'under': 'log', 'invalid': 'log'}
numpy.reference.generated.numpy.seterrcall
numpy.seterrobj numpy.seterrobj(errobj, /) Set the object that defines floating-point error handling. The error object contains all information that defines the error handling behavior in NumPy. seterrobj is used internally by the other functions that set error handling behavior (seterr, seterrcall). Parameters errobjlist The error object, a list containing three elements: [internal numpy buffer size, error mask, error callback function]. The error mask is a single integer that holds the treatment information on all four floating point errors. The information for each error type is contained in three bits of the integer. If we print it in base 8, we can see what treatment is set for “invalid”, “under”, “over”, and “divide” (in that order). The printed string can be interpreted with 0 : ‘ignore’ 1 : ‘warn’ 2 : ‘raise’ 3 : ‘call’ 4 : ‘print’ 5 : ‘log’ See also geterrobj, seterr, geterr, seterrcall, geterrcall getbufsize, setbufsize Notes For complete documentation of the types of floating-point exceptions and treatment options, see seterr. Examples >>> old_errobj = np.geterrobj() # first get the defaults >>> old_errobj [8192, 521, None] >>> def err_handler(type, flag): ... print("Floating point error (%s), with flag %s" % (type, flag)) ... >>> new_errobj = [20000, 12, err_handler] >>> np.seterrobj(new_errobj) >>> np.base_repr(12, 8) # int for divide=4 ('print') and over=1 ('warn') '14' >>> np.geterr() {'over': 'warn', 'divide': 'print', 'invalid': 'ignore', 'under': 'ignore'} >>> np.geterrcall() is err_handler True
numpy.reference.generated.numpy.seterrobj
numpy.setxor1d numpy.setxor1d(ar1, ar2, assume_unique=False)[source] Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays. Parameters ar1, ar2array_like Input arrays. assume_uniquebool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns setxor1dndarray Sorted 1D array of unique values that are in only one of the input arrays. Examples >>> a = np.array([1, 2, 3, 2, 4]) >>> b = np.array([2, 3, 5, 7, 5]) >>> np.setxor1d(a,b) array([1, 4, 5, 7])
numpy.reference.generated.numpy.setxor1d
numpy.shape numpy.shape(a)[source] Return the shape of an array. Parameters aarray_like Input array. Returns shapetuple of ints The elements of the shape tuple give the lengths of the corresponding array dimensions. See also len ndarray.shape Equivalent array method. Examples >>> np.shape(np.eye(3)) (3, 3) >>> np.shape([[1, 2]]) (1, 2) >>> np.shape([0]) (1,) >>> np.shape(0) () >>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')]) >>> np.shape(a) (2,) >>> a.shape (2,)
numpy.reference.generated.numpy.shape
numpy.shares_memory numpy.shares_memory(a, b, /, max_work=None) Determine if two arrays share memory. Warning This function can be exponentially slow for some inputs, unless max_work is set to a finite number or MAY_SHARE_BOUNDS. If in doubt, use numpy.may_share_memory instead. Parameters a, bndarray Input arrays max_workint, optional Effort to spend on solving the overlap problem (maximum number of candidate solutions to consider). The following special values are recognized: max_work=MAY_SHARE_EXACT (default) The problem is solved exactly. In this case, the function returns True only if there is an element shared between the arrays. Finding the exact solution may take extremely long in some cases. max_work=MAY_SHARE_BOUNDS Only the memory bounds of a and b are checked. Returns outbool Raises numpy.TooHardError Exceeded max_work. See also may_share_memory Examples >>> x = np.array([1, 2, 3, 4]) >>> np.shares_memory(x, np.array([5, 6, 7])) False >>> np.shares_memory(x[::2], x) True >>> np.shares_memory(x[::2], x[1::2]) False Checking whether two arrays share memory is NP-complete, and runtime may increase exponentially in the number of dimensions. Hence, max_work should generally be set to a finite number, as it is possible to construct examples that take extremely long to run: >>> from numpy.lib.stride_tricks import as_strided >>> x = np.zeros([192163377], dtype=np.int8) >>> x1 = as_strided(x, strides=(36674, 61119, 85569), shape=(1049, 1049, 1049)) >>> x2 = as_strided(x[64023025:], strides=(12223, 12224, 1), shape=(1049, 1049, 1)) >>> np.shares_memory(x1, x2, max_work=1000) Traceback (most recent call last): ... numpy.TooHardError: Exceeded max_work Running np.shares_memory(x1, x2) without max_work set takes around 1 minute for this case. It is possible to find problems that take still significantly longer.
numpy.reference.generated.numpy.shares_memory
class numpy.short[source] Signed integer type, compatible with C short. Character code 'h' Alias on this platform (Linux x86_64) numpy.int16: 16-bit signed integer (-32_768 to 32_767).
numpy.reference.arrays.scalars#numpy.short
numpy.show_config numpy.show_config()[source] Show libraries in the system on which NumPy was built. Print information about various resources (libraries, library directories, include directories, etc.) in the system on which NumPy was built. See also get_include Returns the directory containing NumPy C header files. Notes Classes specifying the information to be printed are defined in the numpy.distutils.system_info module. Information may include: language: language used to write the libraries (mostly C or f77) libraries: names of libraries found in the system library_dirs: directories containing the libraries include_dirs: directories containing library header files src_dirs: directories containing library source files define_macros: preprocessor macros used by distutils.setup baseline: minimum CPU features required found: dispatched features supported in the system not found: dispatched features that are not supported in the system NumPy BLAS/LAPACK Installation Notes Installing a numpy wheel (pip install numpy or force it via pip install numpy --only-binary :numpy: numpy) includes an OpenBLAS implementation of the BLAS and LAPACK linear algebra APIs. In this case, library_dirs reports the original build time configuration as compiled with gcc/gfortran; at run time the OpenBLAS library is in site-packages/numpy.libs/ (linux), or site-packages/numpy/.dylibs/ (macOS), or site-packages/numpy/.libs/ (windows). Installing numpy from source (pip install numpy --no-binary numpy) searches for BLAS and LAPACK dynamic link libraries at build time as influenced by environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER; or the optional file ~/.numpy-site.cfg. NumPy remembers those locations and expects to load the same libraries at run-time. In NumPy 1.21+ on macOS, ‘accelerate’ (Apple’s Accelerate BLAS library) is in the default build-time search order after ‘openblas’. Examples >>> import numpy as np >>> np.show_config() blas_opt_info: language = c define_macros = [('HAVE_CBLAS', None)] libraries = ['openblas', 'openblas'] library_dirs = ['/usr/local/lib']
numpy.reference.generated.numpy.show_config
numpy.sign numpy.sign(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'sign'> Returns an element-wise indication of the sign of a number. The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0. nan is returned for nan inputs. For complex inputs, the sign function returns sign(x.real) + 0j if x.real != 0 else sign(x.imag) + 0j. complex(nan, 0) is returned for complex nan inputs. Parameters xarray_like Input values. 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 sign of x. This is a scalar if x is a scalar. Notes There is more than one definition of sign in common use for complex numbers. The definition used here is equivalent to \(x/\sqrt{x*x}\) which is different from a common alternative, \(x/|x|\). Examples >>> np.sign([-5., 4.5]) array([-1., 1.]) >>> np.sign(0) 0 >>> np.sign(5-2j) (1+0j)
numpy.reference.generated.numpy.sign
numpy.signbit numpy.signbit(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'signbit'> Returns element-wise True where signbit is set (less than zero). Parameters xarray_like The input value(s). 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 resultndarray of bool Output array, or reference to out if that was supplied. This is a scalar if x is a scalar. Examples >>> np.signbit(-1.2) True >>> np.signbit(np.array([1, -2.3, 2.1])) array([False, True, False])
numpy.reference.generated.numpy.signbit
numpy.sin numpy.sin(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'sin'> Trigonometric sine, element-wise. Parameters xarray_like Angle, in radians (\(2 \pi\) rad equals 360 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 yarray_like The sine of each element of x. This is a scalar if x is a scalar. See also arcsin, sinh, cos Notes The sine is one of the fundamental functions of trigonometry (the mathematical study of triangles). Consider a circle of radius 1 centered on the origin. A ray comes in from the \(+x\) axis, makes an angle at the origin (measured counter-clockwise from that axis), and departs from the origin. The \(y\) coordinate of the outgoing ray’s intersection with the unit circle is the sine of that angle. It ranges from -1 for \(x=3\pi / 2\) to +1 for \(\pi / 2.\) The function has zeroes where the angle is a multiple of \(\pi\). Sines of angles between \(\pi\) and \(2\pi\) are negative. The numerous properties of the sine and related functions are included in any standard trigonometry text. Examples Print sine of one angle: >>> np.sin(np.pi/2.) 1.0 Print sines of an array of angles given in degrees: >>> np.sin(np.array((0., 30., 45., 60., 90.)) * np.pi / 180. ) array([ 0. , 0.5 , 0.70710678, 0.8660254 , 1. ]) Plot the sine function: >>> import matplotlib.pylab as plt >>> x = np.linspace(-np.pi, np.pi, 201) >>> plt.plot(x, np.sin(x)) >>> plt.xlabel('Angle [rad]') >>> plt.ylabel('sin(x)') >>> plt.axis('tight') >>> plt.show()
numpy.reference.generated.numpy.sin
numpy.sinc numpy.sinc(x)[source] Return the normalized sinc function. The sinc function is \(\sin(\pi x)/(\pi x)\). Note Note the normalization factor of pi used in the definition. This is the most commonly used definition in signal processing. Use sinc(x / np.pi) to obtain the unnormalized sinc function \(\sin(x)/(x)\) that is more common in mathematics. Parameters xndarray Array (possibly multi-dimensional) of values for which to to calculate sinc(x). Returns outndarray sinc(x), which has the same shape as the input. Notes sinc(0) is the limit value 1. The name sinc is short for “sine cardinal” or “sinus cardinalis”. The sinc function is used in various signal processing applications, including in anti-aliasing, in the construction of a Lanczos resampling filter, and in interpolation. For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc function. References 1 Weisstein, Eric W. “Sinc Function.” From MathWorld–A Wolfram Web Resource. http://mathworld.wolfram.com/SincFunction.html 2 Wikipedia, “Sinc function”, https://en.wikipedia.org/wiki/Sinc_function Examples >>> import matplotlib.pyplot as plt >>> x = np.linspace(-4, 4, 41) >>> np.sinc(x) array([-3.89804309e-17, -4.92362781e-02, -8.40918587e-02, # may vary -8.90384387e-02, -5.84680802e-02, 3.89804309e-17, 6.68206631e-02, 1.16434881e-01, 1.26137788e-01, 8.50444803e-02, -3.89804309e-17, -1.03943254e-01, -1.89206682e-01, -2.16236208e-01, -1.55914881e-01, 3.89804309e-17, 2.33872321e-01, 5.04551152e-01, 7.56826729e-01, 9.35489284e-01, 1.00000000e+00, 9.35489284e-01, 7.56826729e-01, 5.04551152e-01, 2.33872321e-01, 3.89804309e-17, -1.55914881e-01, -2.16236208e-01, -1.89206682e-01, -1.03943254e-01, -3.89804309e-17, 8.50444803e-02, 1.26137788e-01, 1.16434881e-01, 6.68206631e-02, 3.89804309e-17, -5.84680802e-02, -8.90384387e-02, -8.40918587e-02, -4.92362781e-02, -3.89804309e-17]) >>> plt.plot(x, np.sinc(x)) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Sinc Function") Text(0.5, 1.0, 'Sinc Function') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("X") Text(0.5, 0, 'X') >>> plt.show()
numpy.reference.generated.numpy.sinc
class numpy.single[source] Single-precision floating-point number type, compatible with C float. Character code 'f' Alias on this platform (Linux x86_64) numpy.float32: 32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa.
numpy.reference.arrays.scalars#numpy.single
numpy.singlecomplex[source] alias of numpy.csingle
numpy.reference.arrays.scalars#numpy.singlecomplex
numpy.sinh numpy.sinh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'sinh'> Hyperbolic sine, element-wise. Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(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 yndarray The corresponding hyperbolic sine 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, pg. 83. Examples >>> np.sinh(0) 0.0 >>> np.sinh(np.pi*1j/2) 1j >>> np.sinh(np.pi*1j) # (exact value is 0) 1.2246063538223773e-016j >>> # Discrepancy due to vagaries of floating point arithmetic. >>> # Example of providing the optional output parameter >>> out1 = np.array([0], dtype='d') >>> out2 = np.sinh([0.1], out1) >>> out2 is out1 True >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.sinh(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.sinh
numpy.sort numpy.sort(a, axis=- 1, kind=None, order=None)[source] Return a sorted copy of an array. Parameters aarray_like Array to be sorted. axisint or None, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional Sorting algorithm. The default is ‘quicksort’. Note that both ‘stable’ and ‘mergesort’ use timsort or radix sort under the covers and, in general, the actual implementation will vary with data type. The ‘mergesort’ option is retained for backwards compatibility. Changed in version 1.15.0.: The ‘stable’ option was added. orderstr or list of str, optional When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties. Returns sorted_arrayndarray Array of the same type and shape as a. See also ndarray.sort Method to sort an array in-place. argsort Indirect sort. lexsort Indirect stable sort on multiple keys. searchsorted Find elements in a sorted array. partition Partial sort. Notes The various sorting algorithms are characterized by their average speed, worst case performance, work space size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The four algorithms implemented in NumPy have the following properties: kind speed worst case work space stable ‘quicksort’ 1 O(n^2) 0 no ‘heapsort’ 3 O(n*log(n)) 0 no ‘mergesort’ 2 O(n*log(n)) ~n/2 yes ‘timsort’ 2 O(n*log(n)) ~n/2 yes Note The datatype determines which of ‘mergesort’ or ‘timsort’ is actually used, even if ‘mergesort’ is specified. User selection at a finer scale is not currently available. All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently, sorting along the last axis is faster and uses less space than sorting along any other axis. The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the order is determined by the real parts except when they are equal, in which case the order is determined by the imaginary parts. Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is: Real: [R, nan] Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj] where R is a non-nan real value. Complex values with the same nan placements are sorted according to the non-nan part if it exists. Non-nan values are sorted as before. New in version 1.12.0. quicksort has been changed to introsort. When sorting does not make enough progress it switches to heapsort. This implementation makes quicksort O(n*log(n)) in the worst case. ‘stable’ automatically chooses the best stable sorting algorithm for the data type being sorted. It, along with ‘mergesort’ is currently mapped to timsort or radix sort depending on the data type. API forward compatibility currently limits the ability to select the implementation and it is hardwired for the different data types. New in version 1.17.0. Timsort is added for better performance on already or nearly sorted data. On random data timsort is almost identical to mergesort. It is now used for stable sort while quicksort is still the default sort if none is chosen. For timsort details, refer to CPython listsort.txt. ‘mergesort’ and ‘stable’ are mapped to radix sort for integer data types. Radix sort is an O(n) sort instead of O(n log n). Changed in version 1.18.0. NaT now sorts to the end of arrays for consistency with NaN. Examples >>> a = np.array([[1,4],[3,1]]) >>> np.sort(a) # sort along the last axis array([[1, 4], [1, 3]]) >>> np.sort(a, axis=None) # sort the flattened array array([1, 1, 3, 4]) >>> np.sort(a, axis=0) # sort along the first axis array([[1, 1], [3, 4]]) Use the order keyword to specify a field to use when sorting a structured array: >>> dtype = [('name', 'S10'), ('height', float), ('age', int)] >>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), ... ('Galahad', 1.7, 38)] >>> a = np.array(values, dtype=dtype) # create a structured array >>> np.sort(a, order='height') array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41), ('Lancelot', 1.8999999999999999, 38)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')]) Sort by age, then height if ages are equal: >>> np.sort(a, order=['age', 'height']) array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38), ('Arthur', 1.8, 41)], dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
numpy.reference.generated.numpy.sort
numpy.sort_complex numpy.sort_complex(a)[source] Sort a complex array using the real part first, then the imaginary part. Parameters aarray_like Input array Returns outcomplex ndarray Always returns a sorted complex array. Examples >>> np.sort_complex([5, 3, 6, 2, 1]) array([1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j]) >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j]) array([1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j])
numpy.reference.generated.numpy.sort_complex
numpy.source numpy.source(object, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source] Print or write to a file the source code for a NumPy object. The source code is only returned for objects written in Python. Many functions and classes are defined in C and will therefore not return useful information. Parameters objectnumpy object Input object. This can be any object (function, class, module, …). outputfile object, optional If output not supplied then source code is printed to screen (sys.stdout). File object must be created with either write ‘w’ or append ‘a’ modes. See also lookfor, info Examples >>> np.source(np.interp) In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py def interp(x, xp, fp, left=None, right=None): """.... (full docstring printed)""" if isinstance(x, (float, int, number)): return compiled_interp([x], xp, fp, left, right).item() else: return compiled_interp(x, xp, fp, left, right) The source code is only returned for objects written in Python. >>> np.source(np.array) Not available for this object.
numpy.reference.generated.numpy.source
numpy.spacing numpy.spacing(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'spacing'> Return the distance between x and the nearest adjacent number. Parameters xarray_like Values to find the spacing of. 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 spacing of values of x. This is a scalar if x is a scalar. Notes It can be considered as a generalization of EPS: spacing(np.float64(1)) == np.finfo(np.float64).eps, and there should not be any representable number between x + spacing(x) and x for any finite x. Spacing of +- inf and NaN is NaN. Examples >>> np.spacing(1) == np.finfo(np.float64).eps True
numpy.reference.generated.numpy.spacing
numpy.split numpy.split(ary, indices_or_sections, axis=0)[source] Split an array into multiple sub-arrays as views into ary. Parameters aryndarray Array to be divided into sub-arrays. indices_or_sectionsint or 1-D array If indices_or_sections is an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised. If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis the array is split. For example, [2, 3] would, for axis=0, result in ary[:2] ary[2:3] ary[3:] If an index exceeds the dimension of the array along axis, an empty sub-array is returned correspondingly. axisint, optional The axis along which to split, default is 0. Returns sub-arrayslist of ndarrays A list of sub-arrays as views into ary. Raises ValueError If indices_or_sections is given as an integer, but a split does not result in equal division. See also array_split Split an array into multiple sub-arrays of equal or near-equal size. Does not raise an exception if an equal division cannot be made. 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). concatenate Join a sequence of arrays along an existing axis. stack Join a sequence of arrays along a new axis. 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). Examples >>> x = np.arange(9.0) >>> np.split(x, 3) [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])] >>> x = np.arange(8.0) >>> np.split(x, [3, 5, 6, 10]) [array([0., 1., 2.]), array([3., 4.]), array([5.]), array([6., 7.]), array([], dtype=float64)]
numpy.reference.generated.numpy.split
numpy.sqrt numpy.sqrt(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'sqrt'> Return the non-negative square-root of an array, element-wise. Parameters xarray_like The values whose square-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 positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar. See also lib.scimath.sqrt A version which returns complex numbers when given negative reals. Notes sqrt has–consistent with common convention–as its branch cut the real “interval” [-inf, 0), and is continuous from above on it. A branch cut is a curve in the complex plane across which a given complex function fails to be continuous. Examples >>> np.sqrt([1,4,9]) array([ 1., 2., 3.]) >>> np.sqrt([4, -1, -3+4J]) array([ 2.+0.j, 0.+1.j, 1.+2.j]) >>> np.sqrt([4, -1, np.inf]) array([ 2., nan, inf])
numpy.reference.generated.numpy.sqrt
numpy.square numpy.square(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'square'> Return the element-wise square of the input. 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 outndarray or scalar Element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar. See also numpy.linalg.matrix_power sqrt power Examples >>> np.square([-1j, 1]) array([-1.-0.j, 1.+0.j])
numpy.reference.generated.numpy.square
numpy.squeeze numpy.squeeze(a, axis=None)[source] Remove axes of length one from a. Parameters aarray_like Input data. axisNone or int or tuple of ints, optional New in version 1.7.0. Selects a subset of the entries of length one in the shape. If an axis is selected with shape entry greater than one, an error is raised. Returns squeezedndarray The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a. Note that if all axes are squeezed, the result is a 0d array and not a scalar. Raises ValueError If axis is not None, and an axis being squeezed is not of length 1 See also expand_dims The inverse operation, adding entries of length one reshape Insert, remove, and combine dimensions, and resize existing ones Examples >>> x = np.array([[[0], [1], [2]]]) >>> x.shape (1, 3, 1) >>> np.squeeze(x).shape (3,) >>> np.squeeze(x, axis=0).shape (3, 1) >>> np.squeeze(x, axis=1).shape Traceback (most recent call last): ... ValueError: cannot select an axis to squeeze out which has size not equal to one >>> np.squeeze(x, axis=2).shape (1, 3) >>> x = np.array([[1234]]) >>> x.shape (1, 1) >>> np.squeeze(x) array(1234) # 0d array >>> np.squeeze(x).shape () >>> np.squeeze(x)[()] 1234
numpy.reference.generated.numpy.squeeze
numpy.stack numpy.stack(arrays, axis=0, out=None)[source] Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension. New in version 1.10.0. Parameters arrayssequence of array_like Each array must have the same shape. axisint, optional The axis in the result array along which the input arrays are stacked. outndarray, optional If provided, the destination to place the result. The shape must be correct, matching that of what stack would have returned if no out argument were specified. Returns stackedndarray The stacked array has one more dimension than the input arrays. See also concatenate Join a sequence of arrays along an existing axis. block Assemble an nd-array from nested lists of blocks. split Split array into a list of multiple sub-arrays of equal size. Examples >>> arrays = [np.random.randn(3, 4) for _ in range(10)] >>> np.stack(arrays, axis=0).shape (10, 3, 4) >>> np.stack(arrays, axis=1).shape (3, 10, 4) >>> np.stack(arrays, axis=2).shape (3, 4, 10) >>> a = np.array([1, 2, 3]) >>> b = np.array([4, 5, 6]) >>> np.stack((a, b)) array([[1, 2, 3], [4, 5, 6]]) >>> np.stack((a, b), axis=-1) array([[1, 4], [2, 5], [3, 6]])
numpy.reference.generated.numpy.stack
numpy.std numpy.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)[source] Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis. Parameters aarray_like Calculate the standard deviation of these values. axisNone or int or tuple of ints, optional Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array. New in version 1.7.0. If this is a tuple of ints, a standard deviation is performed over multiple axes, instead of a single axis or all the axes as before. dtypedtype, optional Type to use in computing the standard deviation. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. outndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary. ddofint, optional Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the std method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. wherearray_like of bool, optional Elements to include in the standard deviation. See reduce for details. New in version 1.20.0. Returns standard_deviationndarray, see dtype parameter above. If out is None, return a new array containing the standard deviation, otherwise return a reference to the output array. See also var, mean, nanmean, nanstd, nanvar Output type determination Notes The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std = sqrt(mean(x)), where x = abs(a - a.mean())**2. The average squared deviation is typically calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. The standard deviation computed in this function is the square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard deviation per se. Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real and nonnegative. For floating-point input, the std is computed using the same precision the input has. Depending on the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue. Examples >>> a = np.array([[1, 2], [3, 4]]) >>> np.std(a) 1.1180339887498949 # may vary >>> np.std(a, axis=0) array([1., 1.]) >>> np.std(a, axis=1) array([0.5, 0.5]) In single precision, std() can be inaccurate: >>> a = np.zeros((2, 512*512), dtype=np.float32) >>> a[0, :] = 1.0 >>> a[1, :] = 0.1 >>> np.std(a) 0.45000005 Computing the standard deviation in float64 is more accurate: >>> np.std(a, dtype=np.float64) 0.44999999925494177 # may vary Specifying a where argument: >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]]) >>> np.std(a) 2.614064523559687 # may vary >>> np.std(a, where=[[True], [True], [False]]) 2.0
numpy.reference.generated.numpy.std
class numpy.str_[source] A unicode string. When used in arrays, this type strips trailing null codepoints. Unlike the builtin str, this supports the Buffer Protocol, exposing its contents as UCS4: >>> m = memoryview(np.str_("abc")) >>> m.format '3w' >>> m.tobytes() b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00' Character code 'U' Alias numpy.unicode_
numpy.reference.arrays.scalars#numpy.str_
numpy.string_[source] alias of numpy.bytes_
numpy.reference.arrays.scalars#numpy.string_
numpy.subtract numpy.subtract(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'subtract'> Subtract arguments, element-wise. Parameters x1, x2array_like The arrays to be subtracted from each other. 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 yndarray The difference of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars. Notes Equivalent to x1 - x2 in terms of array broadcasting. Examples >>> np.subtract(1.0, 4.0) -3.0 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.subtract(x1, x2) array([[ 0., 0., 0.], [ 3., 3., 3.], [ 6., 6., 6.]]) The - operator can be used as a shorthand for np.subtract on ndarrays. >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> x1 - x2 array([[0., 0., 0.], [3., 3., 3.], [6., 6., 6.]])
numpy.reference.generated.numpy.subtract
numpy.sum numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)[source] Sum of array elements over a given axis. Parameters aarray_like Elements to sum. axisNone or int or tuple of ints, optional Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. New in version 1.7.0. If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. dtypedtype, optional The type of the returned array and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used. outndarray, optional Alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. keepdimsbool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised. initialscalar, optional Starting value for the sum. See reduce for details. New in version 1.15.0. wherearray_like of bool, optional Elements to include in the sum. See reduce for details. New in version 1.17.0. Returns sum_along_axisndarray An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned. See also ndarray.sum Equivalent method. add.reduce Equivalent functionality of add. cumsum Cumulative sum of array elements. trapz Integration of array values using the composite trapezoidal rule. mean, average Notes Arithmetic is modular when using integer types, and no error is raised on overflow. The sum of an empty array is the neutral element 0: >>> np.sum([]) 0.0 For floating point numbers the numerical precision of sum (and np.add.reduce) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no axis is given. When axis is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python’s math.fsum function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as float32, numerical errors can become significant. In such cases it can be advisable to use dtype=”float64” to use a higher precision for the output. Examples >>> np.sum([0.5, 1.5]) 2.0 >>> np.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) 1 >>> np.sum([[0, 1], [0, 5]]) 6 >>> np.sum([[0, 1], [0, 5]], axis=0) array([0, 6]) >>> np.sum([[0, 1], [0, 5]], axis=1) array([1, 5]) >>> np.sum([[0, 1], [np.nan, 5]], where=[False, True], axis=1) array([1., 5.]) If the accumulator is too small, overflow occurs: >>> np.ones(128, dtype=np.int8).sum(dtype=np.int8) -128 You can also start the sum with a value other than zero: >>> np.sum([10], initial=5) 15
numpy.reference.generated.numpy.sum
numpy.swapaxes numpy.swapaxes(a, axis1, axis2)[source] Interchange two axes of an array. Parameters aarray_like Input array. axis1int First axis. axis2int Second axis. Returns a_swappedndarray For NumPy >= 1.10.0, if a is an ndarray, then a view of a is returned; otherwise a new array is created. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned. Examples >>> x = np.array([[1,2,3]]) >>> np.swapaxes(x,0,1) array([[1], [2], [3]]) >>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]]) >>> x array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.swapaxes(x,0,2) array([[[0, 4], [2, 6]], [[1, 5], [3, 7]]])
numpy.reference.generated.numpy.swapaxes
numpy.take numpy.take(a, indices, axis=None, out=None, mode='raise')[source] Take elements from an array along an axis. When axis is not None, this function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need elements along a given axis. A call such as np.take(arr, indices, axis=3) is equivalent to arr[:,:,:,indices,...]. Explained without fancy indexing, this is equivalent to the following use of ndindex, which sets each of ii, jj, and kk to a tuple of indices: Ni, Nk = a.shape[:axis], a.shape[axis+1:] Nj = indices.shape for ii in ndindex(Ni): for jj in ndindex(Nj): for kk in ndindex(Nk): out[ii + jj + kk] = a[ii + (indices[jj],) + kk] Parameters aarray_like (Ni…, M, Nk…) The source array. indicesarray_like (Nj…) The indices of the values to extract. New in version 1.8.0. Also allow scalars for indices. axisint, optional The axis over which to select values. By default, the flattened input array is used. outndarray, optional (Ni…, Nj…, Nk…) If provided, the result will be placed in 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’, ‘wrap’, ‘clip’}, optional Specifies how out-of-bounds indices will behave. ‘raise’ – raise an error (default) ‘wrap’ – wrap around ‘clip’ – clip to the range ‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. Returns outndarray (Ni…, Nj…, Nk…) The returned array has the same type as a. See also compress Take elements using a boolean mask ndarray.take equivalent method take_along_axis Take elements by matching the array and the index arrays Notes By eliminating the inner loop in the description above, and using s_ to build simple slice objects, take can be expressed in terms of applying fancy indexing to each 1-d slice: Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nj): out[ii + s_[...,] + kk] = a[ii + s_[:,] + kk][indices] For this reason, it is equivalent to (but faster than) the following use of apply_along_axis: out = np.apply_along_axis(lambda a_1d: a_1d[indices], axis, a) Examples >>> a = [4, 3, 5, 7, 6, 8] >>> indices = [0, 1, 4] >>> np.take(a, indices) array([4, 3, 6]) In this example if a is an ndarray, “fancy” indexing can be used. >>> a = np.array(a) >>> a[indices] array([4, 3, 6]) If indices is not one dimensional, the output also has these dimensions. >>> np.take(a, [[0, 1], [2, 3]]) array([[4, 3], [5, 7]])
numpy.reference.generated.numpy.take
numpy.take_along_axis numpy.take_along_axis(arr, indices, axis)[source] Take values from the input array by matching 1d index and data slices. This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to look up values in the latter. These slices can be different lengths. Functions returning an index along an axis, like argsort and argpartition, produce suitable indices for this function. New in version 1.15.0. Parameters arrndarray (Ni…, M, Nk…) Source array indicesndarray (Ni…, J, Nk…) Indices to take along each 1d slice of arr. This must match the dimension of arr, but dimensions Ni and Nj only need to broadcast against arr. axisint The axis to take 1d slices along. If axis is None, the input array is treated as if it had first been flattened to 1d, for consistency with sort and argsort. Returns out: ndarray (Ni…, J, Nk…) The indexed result. See also take Take along an axis, using the same indices for every 1d slice put_along_axis Put values into the destination array by matching 1d index and data slices Notes This is equivalent to (but faster than) the following use of ndindex and s_, which sets each of ii and kk to a tuple of indices: Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:] J = indices.shape[axis] # Need not equal M out = np.empty(Ni + (J,) + Nk) for ii in ndindex(Ni): for kk in ndindex(Nk): a_1d = a [ii + s_[:,] + kk] indices_1d = indices[ii + s_[:,] + kk] out_1d = out [ii + s_[:,] + kk] for j in range(J): out_1d[j] = a_1d[indices_1d[j]] Equivalently, eliminating the inner loop, the last two lines would be: out_1d[:] = a_1d[indices_1d] Examples For this sample array >>> a = np.array([[10, 30, 20], [60, 40, 50]]) We can sort either by using sort directly, or argsort and this function >>> np.sort(a, axis=1) array([[10, 20, 30], [40, 50, 60]]) >>> ai = np.argsort(a, axis=1); ai array([[0, 2, 1], [1, 2, 0]]) >>> np.take_along_axis(a, ai, axis=1) array([[10, 20, 30], [40, 50, 60]]) The same works for max and min, if you expand the dimensions: >>> np.expand_dims(np.max(a, axis=1), axis=1) array([[30], [60]]) >>> ai = np.expand_dims(np.argmax(a, axis=1), axis=1) >>> ai array([[1], [0]]) >>> np.take_along_axis(a, ai, axis=1) array([[30], [60]]) If we want to get the max and min at the same time, we can stack the indices first >>> ai_min = np.expand_dims(np.argmin(a, axis=1), axis=1) >>> ai_max = np.expand_dims(np.argmax(a, axis=1), axis=1) >>> ai = np.concatenate([ai_min, ai_max], axis=1) >>> ai array([[0, 1], [1, 0]]) >>> np.take_along_axis(a, ai, axis=1) array([[10, 30], [40, 60]])
numpy.reference.generated.numpy.take_along_axis
numpy.tan numpy.tan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'tan'> Compute tangent element-wise. Equivalent to np.sin(x)/np.cos(x) element-wise. 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 yndarray The corresponding tangent 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 >>> from math import pi >>> np.tan(np.array([-pi,pi/2,pi])) array([ 1.22460635e-16, 1.63317787e+16, -1.22460635e-16]) >>> >>> # Example of providing the optional output parameter illustrating >>> # that what is returned is a reference to said 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.tan
numpy.tanh numpy.tanh(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'tanh'> Compute hyperbolic tangent element-wise. Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(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 yndarray The corresponding hyperbolic tangent 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 1 M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83. https://personal.math.ubc.ca/~cbm/aands/page_83.htm 2 Wikipedia, “Hyperbolic function”, https://en.wikipedia.org/wiki/Hyperbolic_function Examples >>> np.tanh((0, np.pi*1j, np.pi*1j/2)) array([ 0. +0.00000000e+00j, 0. -1.22460635e-16j, 0. +1.63317787e+16j]) >>> # Example of providing the optional output parameter illustrating >>> # that what is returned is a reference to said parameter >>> out1 = np.array([0], dtype='d') >>> out2 = np.tanh([0.1], out1) >>> out2 is out1 True >>> # Example of ValueError due to provision of shape mis-matched `out` >>> np.tanh(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.tanh
numpy.tensordot numpy.tensordot(a, b, axes=2)[source] Compute tensor dot product along specified axes. Given two tensors, a and b, and an array_like object containing two array_like objects, (a_axes, b_axes), sum the products of a’s and b’s elements (components) over the axes specified by a_axes and b_axes. The third argument can be a single non-negative integer_like scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over. Parameters a, barray_like Tensors to “dot”. axesint or (2,) array_like integer_like If an int N, sum over the last N axes of a and the first N axes of b in order. The sizes of the corresponding axes must match. (2,) array_like Or, a list of axes to be summed over, first sequence applying to a, second to b. Both elements array_like must be of the same length. Returns outputndarray The tensor dot product of the input. See also dot, einsum Notes Three common use cases are: axes = 0 : tensor product \(a\otimes b\) axes = 1 : tensor dot product \(a\cdot b\) axes = 2 : (default) tensor double contraction \(a:b\) When axes is integer_like, the sequence for evaluation will be: first the -Nth axis in a and 0th axis in b, and the -1th axis in a and Nth axis in b last. When there is more than one axis to sum over - and they are not the last (first) axes of a (b) - the argument axes should consist of two sequences of the same length, with the first axis to sum over given first in both sequences, the second axis second, and so forth. The shape of the result consists of the non-contracted axes of the first tensor, followed by the non-contracted axes of the second. Examples A “traditional” example: >>> a = np.arange(60.).reshape(3,4,5) >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape (5, 2) >>> c array([[4400., 4730.], [4532., 4874.], [4664., 5018.], [4796., 5162.], [4928., 5306.]]) >>> # A slower but equivalent way of computing the same... >>> d = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): ... for n in range(4): ... d[i,j] += a[k,n,i] * b[n,k,j] >>> c == d array([[ True, True], [ True, True], [ True, True], [ True, True], [ True, True]]) An extended example taking advantage of the overloading of + and *: >>> a = np.array(range(1, 9)) >>> a.shape = (2, 2, 2) >>> A = np.array(('a', 'b', 'c', 'd'), dtype=object) >>> A.shape = (2, 2) >>> a; A array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) array([['a', 'b'], ['c', 'd']], dtype=object) >>> np.tensordot(a, A) # third argument default is 2 for double-contraction array(['abbcccdddd', 'aaaaabbbbbbcccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, 1) array([[['acc', 'bdd'], ['aaacccc', 'bbbdddd']], [['aaaaacccccc', 'bbbbbdddddd'], ['aaaaaaacccccccc', 'bbbbbbbdddddddd']]], dtype=object) >>> np.tensordot(a, A, 0) # tensor product (result too long to incl.) array([[[[['a', 'b'], ['c', 'd']], ... >>> np.tensordot(a, A, (0, 1)) array([[['abbbbb', 'cddddd'], ['aabbbbbb', 'ccdddddd']], [['aaabbbbbbb', 'cccddddddd'], ['aaaabbbbbbbb', 'ccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, (2, 1)) array([[['abb', 'cdd'], ['aaabbbb', 'cccdddd']], [['aaaaabbbbbb', 'cccccdddddd'], ['aaaaaaabbbbbbbb', 'cccccccdddddddd']]], dtype=object) >>> np.tensordot(a, A, ((0, 1), (0, 1))) array(['abbbcccccddddddd', 'aabbbbccccccdddddddd'], dtype=object) >>> np.tensordot(a, A, ((2, 1), (1, 0))) array(['acccbbdddd', 'aaaaacccccccbbbbbbdddddddd'], dtype=object)
numpy.reference.generated.numpy.tensordot
Testing Guidelines Introduction Until the 1.15 release, NumPy used the nose testing framework, it now uses the pytest framework. The older framework is still maintained in order to support downstream projects that use the old numpy framework, but all tests for NumPy should use pytest. Our goal is that every module and package in NumPy should have a thorough set of unit tests. These tests should exercise the full functionality of a given routine as well as its robustness to erroneous or unexpected input arguments. Well-designed tests with good coverage make an enormous difference to the ease of refactoring. Whenever a new bug is found in a routine, you should write a new test for that specific case and add it to the test suite to prevent that bug from creeping back in unnoticed. Note SciPy uses the testing framework from numpy.testing, so all of the NumPy examples shown below are also applicable to SciPy Testing NumPy NumPy can be tested in a number of ways, choose any way you feel comfortable. Running tests from inside Python You can test an installed NumPy by numpy.test, for example, To run NumPy’s full test suite, use the following: >>> import numpy >>> numpy.test(label='slow') The test method may take two or more arguments; the first label is a string specifying what should be tested and the second verbose is an integer giving the level of output verbosity. See the docstring numpy.test for details. The default value for label is ‘fast’ - which will run the standard tests. The string ‘full’ will run the full battery of tests, including those identified as being slow to run. If verbose is 1 or less, the tests will just show information messages about the tests that are run; but if it is greater than 1, then the tests will also provide warnings on missing tests. So if you want to run every test and get messages about which modules don’t have tests: >>> numpy.test(label='full', verbose=2) # or numpy.test('full', 2) Finally, if you are only interested in testing a subset of NumPy, for example, the core module, use the following: >>> numpy.core.test() Running tests from the command line If you want to build NumPy in order to work on NumPy itself, use runtests.py.To run NumPy’s full test suite: $ python runtests.py Testing a subset of NumPy: $python runtests.py -t numpy/core/tests For detailed info on testing, see Testing builds Other methods of running tests Run tests using your favourite IDE such as vscode or pycharm Writing your own tests If you are writing a package that you’d like to become part of NumPy, please write the tests as you develop the package. Every Python module, extension module, or subpackage in the NumPy package directory should have a corresponding test_<name>.py file. Pytest examines these files for test methods (named test*) and test classes (named Test*). Suppose you have a NumPy module numpy/xxx/yyy.py containing a function zzz(). To test this function you would create a test module called test_yyy.py. If you only need to test one aspect of zzz, you can simply add a test function: def test_zzz(): assert zzz() == 'Hello from zzz' More often, we need to group a number of tests together, so we create a test class: import pytest # import xxx symbols from numpy.xxx.yyy import zzz import pytest class TestZzz: def test_simple(self): assert zzz() == 'Hello from zzz' def test_invalid_parameter(self): with pytest.raises(ValueError, match='.*some matching regex.*'): ... Within these test methods, assert and related functions are used to test whether a certain assumption is valid. If the assertion fails, the test fails. pytest internally rewrites the assert statement to give informative output when it fails, so should be preferred over the legacy variant numpy.testing.assert_. Whereas plain assert statements are ignored when running Python in optimized mode with -O, this is not an issue when running tests with pytest. Similarly, the pytest functions pytest.raises and pytest.warns should be preferred over their legacy counterparts numpy.testing.assert_raises and numpy.testing.assert_warns, since the pytest variants are more broadly used and allow more explicit targeting of warnings and errors when used with the match regex. Note that test_ functions or methods should not have a docstring, because that makes it hard to identify the test from the output of running the test suite with verbose=2 (or similar verbosity setting). Use plain comments (#) if necessary. Also since much of NumPy is legacy code that was originally written without unit tests, there are still several modules that don’t have tests yet. Please feel free to choose one of these modules and develop tests for it. Using C code in tests NumPy exposes a rich C-API . These are tested using c-extension modules written “as-if” they know nothing about the internals of NumPy, rather using the official C-API interfaces only. Examples of such modules are tests for a user-defined rational dtype in _rational_tests or the ufunc machinery tests in _umath_tests which are part of the binary distribution. Starting from version 1.21, you can also write snippets of C code in tests that will be compiled locally into c-extension modules and loaded into python. numpy.testing.extbuild.build_and_import_extension(modname, functions, *, prologue='', build_dir=None, include_dirs=[], more_init='') Build and imports a c-extension module modname from a list of function fragments functions. Parameters functionslist of fragments Each fragment is a sequence of func_name, calling convention, snippet. prologuestring Code to preceed the rest, usually extra #include or #define macros. build_dirpathlib.Path Where to build the module, usually a temporary directory include_dirslist Extra directories to find include files when compiling more_initstring Code to appear in the module PyMODINIT_FUNC Returns out: module The module will have been loaded and is ready for use Examples >>> functions = [("test_bytes", "METH_O", """ if ( !PyBytesCheck(args)) { Py_RETURN_FALSE; } Py_RETURN_TRUE; """)] >>> mod = build_and_import_extension("testme", functions) >>> assert not mod.test_bytes(u'abc') >>> assert mod.test_bytes(b'abc') Labeling tests Unlabeled tests like the ones above are run in the default numpy.test() run. If you want to label your test as slow - and therefore reserved for a full numpy.test(label='full') run, you can label it with pytest.mark.slow: import pytest @pytest.mark.slow def test_big(self): print('Big, slow test') Similarly for methods: class test_zzz: @pytest.mark.slow def test_simple(self): assert_(zzz() == 'Hello from zzz') Easier setup and teardown functions / methods Testing looks for module-level or class-level setup and teardown functions by name; thus: def setup(): """Module-level setup""" print('doing setup') def teardown(): """Module-level teardown""" print('doing teardown') class TestMe: def setup(): """Class-level setup""" print('doing setup') def teardown(): """Class-level teardown""" print('doing teardown') Setup and teardown functions to functions and methods are known as “fixtures”, and their use is not encouraged. Parametric tests One very nice feature of testing is allowing easy testing across a range of parameters - a nasty problem for standard unit tests. Use the pytest.mark.parametrize decorator. Doctests Doctests are a convenient way of documenting the behavior of a function and allowing that behavior to be tested at the same time. The output of an interactive Python session can be included in the docstring of a function, and the test framework can run the example and compare the actual output to the expected output. The doctests can be run by adding the doctests argument to the test() call; for example, to run all tests (including doctests) for numpy.lib: >>> import numpy as np >>> np.lib.test(doctests=True) The doctests are run as if they are in a fresh Python instance which has executed import numpy as np. Tests that are part of a NumPy subpackage will have that subpackage already imported. E.g. for a test in numpy/linalg/tests/, the namespace will be created such that from numpy import linalg has already executed. tests/ Rather than keeping the code and the tests in the same directory, we put all the tests for a given subpackage in a tests/ subdirectory. For our example, if it doesn’t already exist you will need to create a tests/ directory in numpy/xxx/. So the path for test_yyy.py is numpy/xxx/tests/test_yyy.py. Once the numpy/xxx/tests/test_yyy.py is written, its possible to run the tests by going to the tests/ directory and typing: python test_yyy.py Or if you add numpy/xxx/tests/ to the Python path, you could run the tests interactively in the interpreter like this: >>> import test_yyy >>> test_yyy.test() __init__.py and setup.py Usually, however, adding the tests/ directory to the python path isn’t desirable. Instead it would better to invoke the test straight from the module xxx. To this end, simply place the following lines at the end of your package’s __init__.py file: ... def test(level=1, verbosity=1): from numpy.testing import Tester return Tester().test(level, verbosity) You will also need to add the tests directory in the configuration section of your setup.py: ... def configuration(parent_package='', top_path=None): ... config.add_subpackage('tests') return config ... Now you can do the following to test your module: >>> import numpy >>> numpy.xxx.test() Also, when invoking the entire NumPy test suite, your tests will be found and run: >>> import numpy >>> numpy.test() # your tests are included and run automatically! Tips & Tricks Creating many similar tests If you have a collection of tests that must be run multiple times with minor variations, it can be helpful to create a base class containing all the common tests, and then create a subclass for each variation. Several examples of this technique exist in NumPy; below are excerpts from one in numpy/linalg/tests/test_linalg.py: class LinalgTestCase: def test_single(self): a = array([[1., 2.], [3., 4.]], dtype=single) b = array([2., 1.], dtype=single) self.do(a, b) def test_double(self): a = array([[1., 2.], [3., 4.]], dtype=double) b = array([2., 1.], dtype=double) self.do(a, b) ... class TestSolve(LinalgTestCase): def do(self, a, b): x = linalg.solve(a, b) assert_allclose(b, dot(a, x)) assert imply(isinstance(b, matrix), isinstance(x, matrix)) class TestInv(LinalgTestCase): def do(self, a, b): a_inv = linalg.inv(a) assert_allclose(dot(a, a_inv), identity(asarray(a).shape[0])) assert imply(isinstance(a, matrix), isinstance(a_inv, matrix)) In this case, we wanted to test solving a linear algebra problem using matrices of several data types, using linalg.solve and linalg.inv. The common test cases (for single-precision, double-precision, etc. matrices) are collected in LinalgTestCase. Known failures & skipping tests Sometimes you might want to skip a test or mark it as a known failure, such as when the test suite is being written before the code it’s meant to test, or if a test only fails on a particular architecture. To skip a test, simply use skipif: import pytest @pytest.mark.skipif(SkipMyTest, reason="Skipping this test because...") def test_something(foo): ... The test is marked as skipped if SkipMyTest evaluates to nonzero, and the message in verbose test output is the second argument given to skipif. Similarly, a test can be marked as a known failure by using xfail: import pytest @pytest.mark.xfail(MyTestFails, reason="This test is known to fail because...") def test_something_else(foo): ... Of course, a test can be unconditionally skipped or marked as a known failure by using skip or xfail without argument, respectively. A total of the number of skipped and known failing tests is displayed at the end of the test run. Skipped tests are marked as 'S' in the test results (or 'SKIPPED' for verbose > 1), and known failing tests are marked as 'x' (or 'XFAIL' if verbose > 1). Tests on random data Tests on random data are good, but since test failures are meant to expose new bugs or regressions, a test that passes most of the time but fails occasionally with no code changes is not helpful. Make the random data deterministic by setting the random number seed before generating it. Use either Python’s random.seed(some_number) or NumPy’s numpy.random.seed(some_number), depending on the source of random numbers. Alternatively, you can use Hypothesis to generate arbitrary data. Hypothesis manages both Python’s and Numpy’s random seeds for you, and provides a very concise and powerful way to describe data (including hypothesis.extra.numpy, e.g. for a set of mutually-broadcastable shapes). The advantages over random generation include tools to replay and share failures without requiring a fixed seed, reporting minimal examples for each failure, and better-than-naive-random techniques for triggering bugs. Documentation for numpy.test numpy.test(label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, durations=- 1, tests=None) Pytest test runner. A test function is typically added to a package’s __init__.py like so: from numpy._pytesttester import PytestTester test = PytestTester(__name__).test del PytestTester Calling this test function finds and runs all tests associated with the module and all its sub-modules. Parameters module_namemodule name The name of the module to test. Notes Unlike the previous nose-based implementation, this class is not publicly exposed as it performs some numpy-specific warning suppression. Attributes module_namestr Full path to the package to test.
numpy.reference.testing
numpy.testing.suppress_warnings class numpy.testing.suppress_warnings(forwarding_rule='always')[source] Context manager and decorator doing much the same as warnings.catch_warnings. However, it also provides a filter mechanism to work around https://bugs.python.org/issue4180. This bug causes Python before 3.4 to not reliably show warnings again after they have been ignored once (even within catch_warnings). It means that no “ignore” filter can be used easily, since following tests might need to see the warning. Additionally it allows easier specificity for testing warnings and can be nested. Parameters forwarding_rulestr, optional One of “always”, “once”, “module”, or “location”. Analogous to the usual warnings module filter mode, it is useful to reduce noise mostly on the outmost level. Unsuppressed and unrecorded warnings will be forwarded based on this rule. Defaults to “always”. “location” is equivalent to the warnings “default”, match by exact location the warning warning originated from. Notes Filters added inside the context manager will be discarded again when leaving it. Upon entering all filters defined outside a context will be applied automatically. When a recording filter is added, matching warnings are stored in the log attribute as well as in the list returned by record. If filters are added and the module keyword is given, the warning registry of this module will additionally be cleared when applying it, entering the context, or exiting it. This could cause warnings to appear a second time after leaving the context if they were configured to be printed once (default) and were already printed before the context was entered. Nesting this context manager will work as expected when the forwarding rule is “always” (default). Unfiltered and unrecorded warnings will be passed out and be matched by the outer level. On the outmost level they will be printed (or caught by another warnings context). The forwarding rule argument can modify this behaviour. Like catch_warnings this context manager is not threadsafe. Examples With a context manager: with np.testing.suppress_warnings() as sup: sup.filter(DeprecationWarning, "Some text") sup.filter(module=np.ma.core) log = sup.record(FutureWarning, "Does this occur?") command_giving_warnings() # The FutureWarning was given once, the filtered warnings were # ignored. All other warnings abide outside settings (may be # printed/error) assert_(len(log) == 1) assert_(len(sup.log) == 1) # also stored in log attribute Or as a decorator: sup = np.testing.suppress_warnings() sup.filter(module=np.ma.core) # module must match exactly @sup def some_function(): # do something which causes a warning in np.ma.core pass Methods __call__(func) Function decorator to apply certain suppressions to a whole function. filter([category, message, module]) Add a new suppressing filter or apply it if the state is entered. record([category, message, module]) Append a new recording filter or apply it if the state is entered.
numpy.reference.generated.numpy.testing.suppress_warnings
numpy.testing.Tester numpy.testing.Tester[source] alias of numpy.testing._private.nosetester.NoseTester
numpy.reference.generated.numpy.testing.tester
numpy.tile numpy.tile(A, reps)[source] Construct an array by repeating A the number of times given by reps. If reps has length d, the result will have dimension of max(d, A.ndim). If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A to d-dimensions manually before calling this function. If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it. Thus for an A of shape (2, 3, 4, 5), a reps of (2, 2) is treated as (1, 1, 2, 2). Note : Although tile may be used for broadcasting, it is strongly recommended to use numpy’s broadcasting operations and functions. Parameters Aarray_like The input array. repsarray_like The number of repetitions of A along each axis. Returns cndarray The tiled output array. See also repeat Repeat elements of an array. broadcast_to Broadcast an array to a new shape Examples >>> a = np.array([0, 1, 2]) >>> np.tile(a, 2) array([0, 1, 2, 0, 1, 2]) >>> np.tile(a, (2, 2)) array([[0, 1, 2, 0, 1, 2], [0, 1, 2, 0, 1, 2]]) >>> np.tile(a, (2, 1, 2)) array([[[0, 1, 2, 0, 1, 2]], [[0, 1, 2, 0, 1, 2]]]) >>> b = np.array([[1, 2], [3, 4]]) >>> np.tile(b, 2) array([[1, 2, 1, 2], [3, 4, 3, 4]]) >>> np.tile(b, (2, 1)) array([[1, 2], [3, 4], [1, 2], [3, 4]]) >>> c = np.array([1,2,3,4]) >>> np.tile(c,(4,1)) array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
numpy.reference.generated.numpy.tile
class numpy.timedelta64[source] A timedelta stored as a 64-bit integer. See Datetimes and Timedeltas for more information. Character code 'm'
numpy.reference.arrays.scalars#numpy.timedelta64
numpy.trace numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)[source] Return the sum along diagonals of the array. If a is 2-D, the sum along its diagonal with the given offset is returned, i.e., the sum of elements a[i,i+offset] for all i. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting array is the same as that of a with axis1 and axis2 removed. Parameters aarray_like Input array, from which the diagonals are taken. offsetint, optional Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0. axis1, axis2int, optional Axes to be used as the first and second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults are the first two axes of a. dtypedtype, optional Determines the data-type of the returned array and of the accumulator where the elements are summed. If dtype has the value None and a is of integer type of precision less than the default integer precision, then the default integer precision is used. Otherwise, the precision is the same as that of a. outndarray, optional Array into which the output is placed. Its type is preserved and it must be of the right shape to hold the output. Returns sum_along_diagonalsndarray If a is 2-D, the sum along the diagonal is returned. If a has larger dimensions, then an array of sums along diagonals is returned. See also diag, diagonal, diagflat Examples >>> np.trace(np.eye(3)) 3.0 >>> a = np.arange(8).reshape((2,2,2)) >>> np.trace(a) array([6, 8]) >>> a = np.arange(24).reshape((2,2,2,3)) >>> np.trace(a).shape (2, 3)
numpy.reference.generated.numpy.trace
numpy.transpose numpy.transpose(a, axes=None)[source] Reverse or permute the axes of an array; returns the modified array. For an array a with two axes, transpose(a) gives the matrix transpose. Refer to numpy.ndarray.transpose for full documentation. Parameters aarray_like Input array. axestuple or list of ints, optional If specified, it must be a tuple or list which contains a permutation of [0,1,..,N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to the axis numbered axes[i] of the input. If not specified, defaults to range(a.ndim)[::-1], which reverses the order of the axes. Returns pndarray a with its axes permuted. A view is returned whenever possible. See also ndarray.transpose Equivalent method moveaxis argsort Notes Use transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument. Transposing a 1-D array returns an unchanged view of the original array. Examples >>> x = np.arange(4).reshape((2,2)) >>> x array([[0, 1], [2, 3]]) >>> np.transpose(x) array([[0, 2], [1, 3]]) >>> x = np.ones((1, 2, 3)) >>> np.transpose(x, (1, 0, 2)).shape (2, 1, 3) >>> x = np.ones((2, 3, 4, 5)) >>> np.transpose(x).shape (5, 4, 3, 2)
numpy.reference.generated.numpy.transpose
numpy.trapz numpy.trapz(y, x=None, dx=1.0, axis=- 1)[source] Integrate along the given axis using the composite trapezoidal rule. If x is provided, the integration happens in sequence along its elements - they are not sorted. Integrate y (x) along each 1d slice on the given axis, compute \(\int y(x) dx\). When x is specified, this integrates along the parametric curve, computing \(\int_t y(t) dt = \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt\). Parameters yarray_like Input array to integrate. xarray_like, optional The sample points corresponding to the y values. If x is None, the sample points are assumed to be evenly spaced dx apart. The default is None. dxscalar, optional The spacing between sample points when x is None. The default is 1. axisint, optional The axis along which to integrate. Returns trapzfloat or ndarray Definite integral of ‘y’ = n-dimensional array as approximated along a single axis by the trapezoidal rule. If ‘y’ is a 1-dimensional array, then the result is a float. If ‘n’ is greater than 1, then the result is an ‘n-1’ dimensional array. See also sum, cumsum Notes Image [2] illustrates trapezoidal rule – y-axis locations of points will be taken from y array, by default x-axis distances between points will be 1.0, alternatively they can be provided with x array or with dx scalar. Return value will be equal to combined area under the red lines. References 1 Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule 2 Illustration image: https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png Examples >>> np.trapz([1,2,3]) 4.0 >>> np.trapz([1,2,3], x=[4,6,8]) 8.0 >>> np.trapz([1,2,3], dx=2) 8.0 Using a decreasing x corresponds to integrating in reverse: >>> np.trapz([1,2,3], x=[8,6,4]) -8.0 More generally x is used to integrate along a parametric curve. This finds the area of a circle, noting we repeat the sample which closes the curve: >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True) >>> np.trapz(np.cos(theta), x=np.sin(theta)) 3.141571941375841 >>> a = np.arange(6).reshape(2, 3) >>> a array([[0, 1, 2], [3, 4, 5]]) >>> np.trapz(a, axis=0) array([1.5, 2.5, 3.5]) >>> np.trapz(a, axis=1) array([2., 8.])
numpy.reference.generated.numpy.trapz
numpy.tri numpy.tri(N, M=None, k=0, dtype=<class 'float'>, *, like=None)[source] An array with ones at and below the given diagonal and zeros elsewhere. Parameters Nint Number of rows in the array. Mint, optional Number of columns in the array. By default, M is taken equal to N. kint, optional The sub-diagonal at and below which the array is filled. k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0. dtypedtype, optional Data type of the returned array. The default is float. likearray_like Reference object to allow the creation of arrays which are not NumPy arrays. If an array-like passed in as like supports the __array_function__ protocol, the result will be defined by it. In this case, it ensures the creation of an array object compatible with that passed in via this argument. New in version 1.20.0. Returns trindarray of shape (N, M) Array with its lower triangle filled with ones and zero elsewhere; in other words T[i,j] == 1 for j <= i + k, 0 otherwise. Examples >>> np.tri(3, 5, 2, dtype=int) array([[1, 1, 1, 0, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1]]) >>> np.tri(3, 5, -1) array([[0., 0., 0., 0., 0.], [1., 0., 0., 0., 0.], [1., 1., 0., 0., 0.]])
numpy.reference.generated.numpy.tri
numpy.tril numpy.tril(m, k=0)[source] Lower triangle of an array. Return a copy of an array with elements above the k-th diagonal zeroed. For arrays with ndim exceeding 2, tril will apply to the final two axes. Parameters marray_like, shape (…, M, N) Input array. kint, optional Diagonal above which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above. Returns trilndarray, shape (…, M, N) Lower triangle of m, of same shape and data-type as m. See also triu same thing, only for the upper triangle Examples >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 0, 0, 0], [ 4, 0, 0], [ 7, 8, 0], [10, 11, 12]]) >>> np.tril(np.arange(3*4*5).reshape(3, 4, 5)) array([[[ 0, 0, 0, 0, 0], [ 5, 6, 0, 0, 0], [10, 11, 12, 0, 0], [15, 16, 17, 18, 0]], [[20, 0, 0, 0, 0], [25, 26, 0, 0, 0], [30, 31, 32, 0, 0], [35, 36, 37, 38, 0]], [[40, 0, 0, 0, 0], [45, 46, 0, 0, 0], [50, 51, 52, 0, 0], [55, 56, 57, 58, 0]]])
numpy.reference.generated.numpy.tril
numpy.tril_indices numpy.tril_indices(n, k=0, m=None)[source] Return the indices for the lower-triangle of an (n, m) array. Parameters nint The row dimension of the arrays for which the returned indices will be valid. kint, optional Diagonal offset (see tril for details). mint, optional New in version 1.9.0. The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n. Returns indstuple of arrays The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array. See also triu_indices similar function, for upper-triangular. mask_indices generic function accepting an arbitrary mask function. tril, triu Notes New in version 1.4.0. Examples Compute two different sets of indices to access 4x4 arrays, one for the lower triangular part starting at the main diagonal, and one starting two diagonals further right: >>> il1 = np.tril_indices(4) >>> il2 = np.tril_indices(4, 2) Here is how they can be used with a sample array: >>> 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]]) Both for indexing: >>> a[il1] array([ 0, 4, 5, ..., 13, 14, 15]) And for assigning values: >>> a[il1] = -1 >>> a array([[-1, 1, 2, 3], [-1, -1, 6, 7], [-1, -1, -1, 11], [-1, -1, -1, -1]]) These cover almost the whole array (two diagonals right of the main one): >>> a[il2] = -10 >>> a array([[-10, -10, -10, 3], [-10, -10, -10, -10], [-10, -10, -10, -10], [-10, -10, -10, -10]])
numpy.reference.generated.numpy.tril_indices
numpy.tril_indices_from numpy.tril_indices_from(arr, k=0)[source] Return the indices for the lower-triangle of arr. See tril_indices for full details. Parameters arrarray_like The indices will be valid for square arrays whose dimensions are the same as arr. kint, optional Diagonal offset (see tril for details). See also tril_indices, tril Notes New in version 1.4.0.
numpy.reference.generated.numpy.tril_indices_from
numpy.trim_zeros numpy.trim_zeros(filt, trim='fb')[source] Trim the leading and/or trailing zeros from a 1-D array or sequence. Parameters filt1-D array or sequence Input array. trimstr, optional A string with ‘f’ representing trim from front and ‘b’ to trim from back. Default is ‘fb’, trim zeros from both front and back of the array. Returns trimmed1-D array or sequence The result of trimming the input. The input data type is preserved. Examples >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0)) >>> np.trim_zeros(a) array([1, 2, 3, 0, 2, 1]) >>> np.trim_zeros(a, 'b') array([0, 0, 0, ..., 0, 2, 1]) The input data type is preserved, list/tuple in means list/tuple out. >>> np.trim_zeros([0, 1, 2, 0]) [1, 2]
numpy.reference.generated.numpy.trim_zeros
numpy.triu numpy.triu(m, k=0)[source] Upper triangle of an array. Return a copy of an array with the elements below the k-th diagonal zeroed. For arrays with ndim exceeding 2, triu will apply to the final two axes. Please refer to the documentation for tril for further details. See also tril lower triangle of an array Examples >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 1, 2, 3], [ 4, 5, 6], [ 0, 8, 9], [ 0, 0, 12]]) >>> np.triu(np.arange(3*4*5).reshape(3, 4, 5)) array([[[ 0, 1, 2, 3, 4], [ 0, 6, 7, 8, 9], [ 0, 0, 12, 13, 14], [ 0, 0, 0, 18, 19]], [[20, 21, 22, 23, 24], [ 0, 26, 27, 28, 29], [ 0, 0, 32, 33, 34], [ 0, 0, 0, 38, 39]], [[40, 41, 42, 43, 44], [ 0, 46, 47, 48, 49], [ 0, 0, 52, 53, 54], [ 0, 0, 0, 58, 59]]])
numpy.reference.generated.numpy.triu
numpy.triu_indices numpy.triu_indices(n, k=0, m=None)[source] Return the indices for the upper-triangle of an (n, m) array. Parameters nint The size of the arrays for which the returned indices will be valid. kint, optional Diagonal offset (see triu for details). mint, optional New in version 1.9.0. The column dimension of the arrays for which the returned arrays will be valid. By default m is taken equal to n. Returns indstuple, shape(2) of ndarrays, shape(n) The indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array. Can be used to slice a ndarray of shape(n, n). See also tril_indices similar function, for lower-triangular. mask_indices generic function accepting an arbitrary mask function. triu, tril Notes New in version 1.4.0. Examples Compute two different sets of indices to access 4x4 arrays, one for the upper triangular part starting at the main diagonal, and one starting two diagonals further right: >>> iu1 = np.triu_indices(4) >>> iu2 = np.triu_indices(4, 2) Here is how they can be used with a sample array: >>> 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]]) Both for indexing: >>> a[iu1] array([ 0, 1, 2, ..., 10, 11, 15]) And for assigning values: >>> a[iu1] = -1 >>> a array([[-1, -1, -1, -1], [ 4, -1, -1, -1], [ 8, 9, -1, -1], [12, 13, 14, -1]]) These cover only a small part of the whole array (two diagonals right of the main one): >>> a[iu2] = -10 >>> a array([[ -1, -1, -10, -10], [ 4, -1, -1, -10], [ 8, 9, -1, -1], [ 12, 13, 14, -1]])
numpy.reference.generated.numpy.triu_indices
numpy.triu_indices_from numpy.triu_indices_from(arr, k=0)[source] Return the indices for the upper-triangle of arr. See triu_indices for full details. Parameters arrndarray, shape(N, N) The indices will be valid for square arrays. kint, optional Diagonal offset (see triu for details). Returns triu_indices_fromtuple, shape(2) of ndarray, shape(N) Indices for the upper-triangle of arr. See also triu_indices, triu Notes New in version 1.4.0.
numpy.reference.generated.numpy.triu_indices_from
numpy.true_divide numpy.true_divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'true_divide'> Returns a true division of the inputs, element-wise. Unlike ‘floor division’, true division adjusts the output type to present the best answer, regardless of input types. Parameters x1array_like Dividend array. x2array_like Divisor array. 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 This is a scalar if both x1 and x2 are scalars. Notes In Python, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python. Examples >>> x = np.arange(5) >>> np.true_divide(x, 4) array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x/4 array([ 0. , 0.25, 0.5 , 0.75, 1. ]) >>> x//4 array([0, 0, 0, 0, 1]) The / operator can be used as a shorthand for np.true_divide on ndarrays. >>> x = np.arange(5) >>> x / 4 array([0. , 0.25, 0.5 , 0.75, 1. ])
numpy.reference.generated.numpy.true_divide
numpy.trunc numpy.trunc(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'trunc'> Return the truncated value of the input, element-wise. The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. In short, the fractional part of the signed number x is discarded. 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 truncated value of each element in x. This is a scalar if x is a scalar. See also ceil, floor, rint, fix Notes New in version 1.3.0. Examples >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.trunc(a) array([-1., -1., -0., 0., 1., 1., 2.])
numpy.reference.generated.numpy.trunc