doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
numpy.histogram2d numpy.histogram2d(x, y, bins=10, range=None, normed=None, weights=None, density=None)[source] Compute the bi-dimensional histogram of two data samples. Parameters xarray_like, shape (N,) An array containing the x coordinates of the points to be histogrammed. yarray_like, shape (N,) An array containing the y coordinates of the points to be histogrammed. binsint or array_like or [int, int] or [array, array], optional The bin specification: If int, the number of bins for the two dimensions (nx=ny=bins). If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins). If [int, int], the number of bins in each dimension (nx, ny = bins). If [array, array], the bin edges in each dimension (x_edges, y_edges = bins). A combination [int, array] or [array, int], where int is the number of bins and array is the bin edges. rangearray_like, shape(2,2), optional The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the bins parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram. densitybool, optional If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_area. normedbool, optional An alias for the density argument that behaves identically. To avoid confusion with the broken normed argument to histogram, density should be preferred. weightsarray_like, shape(N,), optional An array of values w_i weighing each sample (x_i, y_i). Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin. Returns Hndarray, shape(nx, ny) The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension. xedgesndarray, shape(nx+1,) The bin edges along the first dimension. yedgesndarray, shape(ny+1,) The bin edges along the second dimension. See also histogram 1D histogram histogramdd Multidimensional histogram Notes When normed is True, then the returned histogram is the sample density, defined such that the sum over bins of the product bin_value * bin_area is 1. Please note that the histogram does not follow the Cartesian convention where x values are on the abscissa and y values on the ordinate axis. Rather, x is histogrammed along the first dimension of the array (vertical), and y along the second dimension of the array (horizontal). This ensures compatibility with histogramdd. Examples >>> from matplotlib.image import NonUniformImage >>> import matplotlib.pyplot as plt Construct a 2-D histogram with variable bin width. First define the bin edges: >>> xedges = [0, 1, 3, 5] >>> yedges = [0, 2, 3, 4, 6] Next we create a histogram H with random bin content: >>> x = np.random.normal(2, 1, 100) >>> y = np.random.normal(1, 1, 100) >>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges)) >>> # Histogram does not follow Cartesian convention (see Notes), >>> # therefore transpose H for visualization purposes. >>> H = H.T imshow can only display square bins: >>> fig = plt.figure(figsize=(7, 3)) >>> ax = fig.add_subplot(131, title='imshow: square bins') >>> plt.imshow(H, interpolation='nearest', origin='lower', ... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]]) <matplotlib.image.AxesImage object at 0x...> pcolormesh can display actual edges: >>> ax = fig.add_subplot(132, title='pcolormesh: actual edges', ... aspect='equal') >>> X, Y = np.meshgrid(xedges, yedges) >>> ax.pcolormesh(X, Y, H) <matplotlib.collections.QuadMesh object at 0x...> NonUniformImage can be used to display actual bin edges with interpolation: >>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated', ... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) >>> im = NonUniformImage(ax, interpolation='bilinear') >>> xcenters = (xedges[:-1] + xedges[1:]) / 2 >>> ycenters = (yedges[:-1] + yedges[1:]) / 2 >>> im.set_data(xcenters, ycenters, H) >>> ax.images.append(im) >>> plt.show() It is also possible to construct a 2-D histogram without specifying bin edges: >>> # Generate non-symmetric test data >>> n = 10000 >>> x = np.linspace(1, 100, n) >>> y = 2*np.log(x) + np.random.rand(n) - 0.5 >>> # Compute 2d histogram. Note the order of x/y and xedges/yedges >>> H, yedges, xedges = np.histogram2d(y, x, bins=20) Now we can plot the histogram using pcolormesh, and a hexbin for comparison. >>> # Plot histogram using pcolormesh >>> fig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True) >>> ax1.pcolormesh(xedges, yedges, H, cmap='rainbow') >>> ax1.plot(x, 2*np.log(x), 'k-') >>> ax1.set_xlim(x.min(), x.max()) >>> ax1.set_ylim(y.min(), y.max()) >>> ax1.set_xlabel('x') >>> ax1.set_ylabel('y') >>> ax1.set_title('histogram2d') >>> ax1.grid() >>> # Create hexbin plot for comparison >>> ax2.hexbin(x, y, gridsize=20, cmap='rainbow') >>> ax2.plot(x, 2*np.log(x), 'k-') >>> ax2.set_title('hexbin') >>> ax2.set_xlim(x.min(), x.max()) >>> ax2.set_xlabel('x') >>> ax2.grid() >>> plt.show()
numpy.reference.generated.numpy.histogram2d
numpy.histogram_bin_edges numpy.histogram_bin_edges(a, bins=10, range=None, weights=None)[source] Function to calculate only the edges of the bins used by the histogram function. Parameters aarray_like Input data. The histogram is computed over the flattened array. binsint or sequence of scalars or str, optional If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. If bins is a string from the list below, histogram_bin_edges will use the method chosen to calculate the optimal bin width and consequently the number of bins (see Notes for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the ‘auto’ option is suggested. Weighted data is not supported for automated bin size selection. ‘auto’ Maximum of the ‘sturges’ and ‘fd’ estimators. Provides good all around performance. ‘fd’ (Freedman Diaconis Estimator) Robust (resilient to outliers) estimator that takes into account data variability and data size. ‘doane’ An improved version of Sturges’ estimator that works better with non-normal datasets. ‘scott’ Less robust estimator that that takes into account data variability and data size. ‘stone’ Estimator based on leave-one-out cross-validation estimate of the integrated squared error. Can be regarded as a generalization of Scott’s rule. ‘rice’ Estimator does not take variability into account, only data size. Commonly overestimates number of bins required. ‘sturges’ R’s default method, only accounts for data size. Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets. ‘sqrt’ Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity. range(float, float), optional The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data. weightsarray_like, optional An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1). This is currently not used by any of the bin estimators, but may be in the future. Returns bin_edgesarray of dtype float The edges to pass into histogram See also histogram Notes The methods to estimate the optimal number of bins are well founded in literature, and are inspired by the choices R provides for histogram visualisation. Note that having the number of bins proportional to \(n^{1/3}\) is asymptotically optimal, which is why it appears in most estimators. These are simply plug-in methods that give good starting points for number of bins. In the equations below, \(h\) is the binwidth and \(n_h\) is the number of bins. All estimators that compute bin counts are recast to bin width using the ptp of the data. The final bin count is obtained from np.round(np.ceil(range / h)). The final bin width is often less than what is returned by the estimators below. ‘auto’ (maximum of the ‘sturges’ and ‘fd’ estimators) A compromise to get a good value. For small datasets the Sturges value will usually be chosen, while larger datasets will usually default to FD. Avoids the overly conservative behaviour of FD and Sturges for small and large datasets respectively. Switchover point is usually \(a.size \approx 1000\). ‘fd’ (Freedman Diaconis Estimator) \[h = 2 \frac{IQR}{n^{1/3}}\] The binwidth is proportional to the interquartile range (IQR) and inversely proportional to cube root of a.size. Can be too conservative for small datasets, but is quite good for large datasets. The IQR is very robust to outliers. ‘scott’ \[h = \sigma \sqrt[3]{\frac{24 * \sqrt{\pi}}{n}}\] The binwidth is proportional to the standard deviation of the data and inversely proportional to cube root of x.size. Can be too conservative for small datasets, but is quite good for large datasets. The standard deviation is not very robust to outliers. Values are very similar to the Freedman-Diaconis estimator in the absence of outliers. ‘rice’ \[n_h = 2n^{1/3}\] The number of bins is only proportional to cube root of a.size. It tends to overestimate the number of bins and it does not take into account data variability. ‘sturges’ \[n_h = \log _{2}n+1\] The number of bins is the base 2 log of a.size. This estimator assumes normality of data and is too conservative for larger, non-normal datasets. This is the default method in R’s hist method. ‘doane’ \[ \begin{align}\begin{aligned}n_h = 1 + \log_{2}(n) + \log_{2}(1 + \frac{|g_1|}{\sigma_{g_1}})\\g_1 = mean[(\frac{x - \mu}{\sigma})^3]\\\sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}}\end{aligned}\end{align} \] An improved version of Sturges’ formula that produces better estimates for non-normal datasets. This estimator attempts to account for the skew of the data. ‘sqrt’ \[n_h = \sqrt n\] The simplest and fastest estimator. Only takes into account the data size. Examples >>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5]) >>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1)) array([0. , 0.25, 0.5 , 0.75, 1. ]) >>> np.histogram_bin_edges(arr, bins=2) array([0. , 2.5, 5. ]) For consistency with histogram, an array of pre-computed bins is passed through unmodified: >>> np.histogram_bin_edges(arr, [1, 2]) array([1, 2]) This function allows one set of bins to be computed, and reused across multiple histograms: >>> shared_bins = np.histogram_bin_edges(arr, bins='auto') >>> shared_bins array([0., 1., 2., 3., 4., 5.]) >>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1]) >>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins) >>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins) >>> hist_0; hist_1 array([1, 1, 0, 1, 0]) array([2, 0, 1, 1, 2]) Which gives more easily comparable results than using separate bins for each histogram: >>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto') >>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto') >>> hist_0; hist_1 array([1, 1, 1]) array([2, 1, 1, 2]) >>> bins_0; bins_1 array([0., 1., 2., 3.]) array([0. , 1.25, 2.5 , 3.75, 5. ])
numpy.reference.generated.numpy.histogram_bin_edges
numpy.histogramdd numpy.histogramdd(sample, bins=10, range=None, normed=None, weights=None, density=None)[source] Compute the multidimensional histogram of some data. Parameters sample(N, D) array, or (D, N) array_like The data to be histogrammed. Note the unusual interpretation of sample when an array_like: When an array, each row is a coordinate in a D-dimensional space - such as histogramdd(np.array([p1, p2, p3])). When an array_like, each element is the list of values for single coordinate - such as histogramdd((X, Y, Z)). The first form should be preferred. binssequence or int, optional The bin specification: A sequence of arrays describing the monotonically increasing bin edges along each dimension. The number of bins for each dimension (nx, ny, … =bins) The number of bins for all dimensions (nx=ny=…=bins). rangesequence, optional A sequence of length D, each an optional (lower, upper) tuple giving the outer bin edges to be used if the edges are not given explicitly in bins. An entry of None in the sequence results in the minimum and maximum values being used for the corresponding dimension. The default, None, is equivalent to passing a tuple of D None values. densitybool, optional If False, the default, returns the number of samples in each bin. If True, returns the probability density function at the bin, bin_count / sample_count / bin_volume. normedbool, optional An alias for the density argument that behaves identically. To avoid confusion with the broken normed argument to histogram, density should be preferred. weights(N,) array_like, optional An array of values w_i weighing each sample (x_i, y_i, z_i, …). Weights are normalized to 1 if normed is True. If normed is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin. Returns Hndarray The multidimensional histogram of sample x. See normed and weights for the different possible semantics. edgeslist A list of D arrays describing the bin edges for each dimension. See also histogram 1-D histogram histogram2d 2-D histogram Examples >>> r = np.random.randn(100,3) >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) >>> H.shape, edges[0].size, edges[1].size, edges[2].size ((5, 8, 4), 6, 9, 5)
numpy.reference.generated.numpy.histogramdd
numpy.hsplit numpy.hsplit(ary, indices_or_sections)[source] Split an array into multiple sub-arrays horizontally (column-wise). Please refer to the split documentation. hsplit is equivalent to split with axis=1, the array is always split along the second axis regardless of the array dimension. See also split Split an array into multiple sub-arrays of equal size. Examples >>> x = np.arange(16.0).reshape(4, 4) >>> x array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.hsplit(x, 2) [array([[ 0., 1.], [ 4., 5.], [ 8., 9.], [12., 13.]]), array([[ 2., 3.], [ 6., 7.], [10., 11.], [14., 15.]])] >>> np.hsplit(x, np.array([3, 6])) [array([[ 0., 1., 2.], [ 4., 5., 6.], [ 8., 9., 10.], [12., 13., 14.]]), array([[ 3.], [ 7.], [11.], [15.]]), array([], shape=(4, 0), dtype=float64)] With a higher dimensional array the split is still along the second axis. >>> x = np.arange(8.0).reshape(2, 2, 2) >>> x array([[[0., 1.], [2., 3.]], [[4., 5.], [6., 7.]]]) >>> np.hsplit(x, 2) [array([[[0., 1.]], [[4., 5.]]]), array([[[2., 3.]], [[6., 7.]]])]
numpy.reference.generated.numpy.hsplit
numpy.hstack numpy.hstack(tup)[source] Stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis. Rebuilds arrays divided by hsplit. 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 second axis, except 1-D arrays which can be any length. Returns stackedndarray The array formed by stacking the given arrays. 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. vstack Stack arrays in sequence vertically (row wise). dstack Stack arrays in sequence depth wise (along third axis). column_stack Stack 1-D arrays as columns into a 2-D array. hsplit Split an array into multiple sub-arrays horizontally (column-wise). Examples >>> a = np.array((1,2,3)) >>> b = np.array((4,5,6)) >>> np.hstack((a,b)) array([1, 2, 3, 4, 5, 6]) >>> a = np.array([[1],[2],[3]]) >>> b = np.array([[4],[5],[6]]) >>> np.hstack((a,b)) array([[1, 4], [2, 5], [3, 6]])
numpy.reference.generated.numpy.hstack
numpy.hypot numpy.hypot(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'hypot'> Given the “legs” of a right triangle, return its hypotenuse. Equivalent to sqrt(x1**2 + x2**2), element-wise. If x1 or x2 is scalar_like (i.e., unambiguously cast-able to a scalar type), it is broadcast for use with each element of the other argument. (See Examples) Parameters x1, x2array_like Leg of the triangle(s). 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 zndarray The hypotenuse of the triangle(s). This is a scalar if both x1 and x2 are scalars. Examples >>> np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3))) array([[ 5., 5., 5.], [ 5., 5., 5.], [ 5., 5., 5.]]) Example showing broadcast of scalar_like argument: >>> np.hypot(3*np.ones((3, 3)), [4]) array([[ 5., 5., 5.], [ 5., 5., 5.], [ 5., 5., 5.]])
numpy.reference.generated.numpy.hypot
numpy.i0 numpy.i0(x)[source] Modified Bessel function of the first kind, order 0. Usually denoted \(I_0\). Parameters xarray_like of float Argument of the Bessel function. Returns outndarray, shape = x.shape, dtype = float The modified Bessel function evaluated at each of the elements of x. See also scipy.special.i0, scipy.special.iv, scipy.special.ive Notes The scipy implementation is recommended over this function: it is a proper ufunc written in C, and more than an order of magnitude faster. We use the algorithm published by Clenshaw [1] and referenced by Abramowitz and Stegun [2], for which the function domain is partitioned into the two intervals [0,8] and (8,inf), and Chebyshev polynomial expansions are employed in each interval. Relative error on the domain [0,30] using IEEE arithmetic is documented [3] as having a peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000). References 1 C. W. Clenshaw, “Chebyshev series for mathematical functions”, in National Physical Laboratory Mathematical Tables, vol. 5, London: Her Majesty’s Stationery Office, 1962. 2 M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions, 10th printing, New York: Dover, 1964, pp. 379. https://personal.math.ubc.ca/~cbm/aands/page_379.htm 3 https://metacpan.org/pod/distribution/Math-Cephes/lib/Math/Cephes.pod#i0:-Modified-Bessel-function-of-order-zero Examples >>> np.i0(0.) array(1.0) >>> np.i0([0, 1, 2, 3]) array([1. , 1.26606588, 2.2795853 , 4.88079259])
numpy.reference.generated.numpy.i0
numpy.identity numpy.identity(n, dtype=None, *, like=None)[source] Return the identity array. The identity array is a square array with ones on the main diagonal. Parameters nint Number of rows (and columns) in n x n output. dtypedata-type, optional Data-type of the output. Defaults to 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 outndarray n x n array with its main diagonal set to one, and all other elements 0. Examples >>> np.identity(3) array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
numpy.reference.generated.numpy.identity
numpy.iinfo class numpy.iinfo(type)[source] Machine limits for integer types. Parameters int_typeinteger type, dtype, or instance The kind of integer data type to get information about. See also finfo The equivalent for floating point data types. Examples With types: >>> ii16 = np.iinfo(np.int16) >>> ii16.min -32768 >>> ii16.max 32767 >>> ii32 = np.iinfo(np.int32) >>> ii32.min -2147483648 >>> ii32.max 2147483647 With instances: >>> ii32 = np.iinfo(np.int32(10)) >>> ii32.min -2147483648 >>> ii32.max 2147483647 Attributes bitsint The number of bits occupied by the type. minint Minimum value of given dtype. maxint Maximum value of given dtype.
numpy.reference.generated.numpy.iinfo
numpy.imag numpy.imag(val)[source] Return the imaginary part of the complex argument. Parameters valarray_like Input array. Returns outndarray or scalar The imaginary 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, angle, real_if_close Examples >>> a = np.array([1+2j, 3+4j, 5+6j]) >>> a.imag array([2., 4., 6.]) >>> a.imag = np.array([8, 10, 12]) >>> a array([1. +8.j, 3.+10.j, 5.+12.j]) >>> np.imag(1 + 1j) 1.0
numpy.reference.generated.numpy.imag
numpy.in1d numpy.in1d(ar1, ar2, assume_unique=False, invert=False)[source] Test whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise. We recommend using isin instead of in1d for new code. Parameters ar1(M,) array_like Input array. ar2array_like The values against which to test each value of ar1. assume_uniquebool, optional If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. invertbool, optional If True, the values in the returned array are inverted (that is, False where an element of ar1 is in ar2 and True otherwise). Default is False. np.in1d(a, b, invert=True) is equivalent to (but is faster than) np.invert(in1d(a, b)). New in version 1.8.0. Returns in1d(M,) ndarray, bool The values ar1[in1d] are in ar2. See also isin Version of this function that preserves the shape of ar1. numpy.lib.arraysetops Module with a number of other functions for performing set operations on arrays. Notes in1d can be considered as an element-wise function version of the python keyword in, for 1-D sequences. in1d(a, b) is roughly equivalent to np.array([item in b for item in a]). However, this idea fails if ar2 is a set, or similar (non-sequence) container: As ar2 is converted to an array, in those cases asarray(ar2) is an object array rather than the expected array of contained values. New in version 1.4.0. Examples >>> test = np.array([0, 1, 2, 5, 0]) >>> states = [0, 2] >>> mask = np.in1d(test, states) >>> mask array([ True, False, True, False, True]) >>> test[mask] array([0, 2, 0]) >>> mask = np.in1d(test, states, invert=True) >>> mask array([False, True, False, True, False]) >>> test[mask] array([1, 5])
numpy.reference.generated.numpy.in1d
numpy.indices numpy.indices(dimensions, dtype=<class 'int'>, sparse=False)[source] Return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis. Parameters dimensionssequence of ints The shape of the grid. dtypedtype, optional Data type of the result. sparseboolean, optional Return a sparse representation of the grid instead of a dense representation. Default is False. New in version 1.17. Returns gridone ndarray or tuple of ndarrays If sparse is False: Returns one array of grid indices, grid.shape = (len(dimensions),) + tuple(dimensions). If sparse is True: Returns a tuple of arrays, with grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1) with dimensions[i] in the ith place See also mgrid, ogrid, meshgrid Notes The output shape in the dense case is obtained by prepending the number of dimensions in front of the tuple of dimensions, i.e. if dimensions is a tuple (r0, ..., rN-1) of length N, the output shape is (N, r0, ..., rN-1). The subarrays grid[k] contains the N-D array of indices along the k-th axis. Explicitly: grid[k, i0, i1, ..., iN-1] = ik Examples >>> grid = np.indices((2, 3)) >>> grid.shape (2, 2, 3) >>> grid[0] # row indices array([[0, 0, 0], [1, 1, 1]]) >>> grid[1] # column indices array([[0, 1, 2], [0, 1, 2]]) The indices can be used as an index into an array. >>> x = np.arange(20).reshape(5, 4) >>> row, col = np.indices((2, 3)) >>> x[row, col] array([[0, 1, 2], [4, 5, 6]]) Note that it would be more straightforward in the above example to extract the required elements directly with x[:2, :3]. If sparse is set to true, the grid will be returned in a sparse representation. >>> i, j = np.indices((2, 3), sparse=True) >>> i.shape (2, 1) >>> j.shape (1, 3) >>> i # row indices array([[0], [1]]) >>> j # column indices array([[0, 1, 2]])
numpy.reference.generated.numpy.indices
Constants NumPy includes several constants: numpy.Inf IEEE 754 floating point representation of (positive) infinity. Use inf because Inf, Infinity, PINF and infty are aliases for inf. For more details, see inf. See Also inf numpy.Infinity IEEE 754 floating point representation of (positive) infinity. Use inf because Inf, Infinity, PINF and infty are aliases for inf. For more details, see inf. See Also inf numpy.NAN IEEE 754 floating point representation of Not a Number (NaN). NaN and NAN are equivalent definitions of nan. Please use nan instead of NAN. See Also nan numpy.NINF IEEE 754 floating point representation of negative infinity. Returns yfloat A floating point representation of negative infinity. See Also isinf : Shows which elements are positive or negative infinity isposinf : Shows which elements are positive infinity isneginf : Shows which elements are negative infinity isnan : Shows which elements are Not a Number isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity is equivalent to positive infinity. Examples >>> np.NINF -inf >>> np.log(0) -inf numpy.NZERO IEEE 754 floating point representation of negative zero. Returns yfloat A floating point representation of negative zero. See Also PZERO : Defines positive zero. isinf : Shows which elements are positive or negative infinity. isposinf : Shows which elements are positive infinity. isneginf : Shows which elements are negative infinity. isnan : Shows which elements are Not a Number. isfiniteShows which elements are finite - not one of Not a Number, positive infinity and negative infinity. Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Negative zero is considered to be a finite number. Examples >>> np.NZERO -0.0 >>> np.PZERO 0.0 >>> np.isfinite([np.NZERO]) array([ True]) >>> np.isnan([np.NZERO]) array([False]) >>> np.isinf([np.NZERO]) array([False]) numpy.NaN IEEE 754 floating point representation of Not a Number (NaN). NaN and NAN are equivalent definitions of nan. Please use nan instead of NaN. See Also nan numpy.PINF IEEE 754 floating point representation of (positive) infinity. Use inf because Inf, Infinity, PINF and infty are aliases for inf. For more details, see inf. See Also inf numpy.PZERO IEEE 754 floating point representation of positive zero. Returns yfloat A floating point representation of positive zero. See Also NZERO : Defines negative zero. isinf : Shows which elements are positive or negative infinity. isposinf : Shows which elements are positive infinity. isneginf : Shows which elements are negative infinity. isnan : Shows which elements are Not a Number. isfiniteShows which elements are finite - not one of Not a Number, positive infinity and negative infinity. Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Positive zero is considered to be a finite number. Examples >>> np.PZERO 0.0 >>> np.NZERO -0.0 >>> np.isfinite([np.PZERO]) array([ True]) >>> np.isnan([np.PZERO]) array([False]) >>> np.isinf([np.PZERO]) array([False]) numpy.e Euler’s constant, base of natural logarithms, Napier’s constant. e = 2.71828182845904523536028747135266249775724709369995... See Also exp : Exponential function log : Natural logarithm References https://en.wikipedia.org/wiki/E_%28mathematical_constant%29 numpy.euler_gamma γ = 0.5772156649015328606065120900824024310421... References https://en.wikipedia.org/wiki/Euler-Mascheroni_constant numpy.inf IEEE 754 floating point representation of (positive) infinity. Returns yfloat A floating point representation of positive infinity. See Also isinf : Shows which elements are positive or negative infinity isposinf : Shows which elements are positive infinity isneginf : Shows which elements are negative infinity isnan : Shows which elements are Not a Number isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity is equivalent to positive infinity. Inf, Infinity, PINF and infty are aliases for inf. Examples >>> np.inf inf >>> np.array([1]) / 0. array([ Inf]) numpy.infty IEEE 754 floating point representation of (positive) infinity. Use inf because Inf, Infinity, PINF and infty are aliases for inf. For more details, see inf. See Also inf numpy.nan IEEE 754 floating point representation of Not a Number (NaN). Returns y : A floating point representation of Not a Number. See Also isnan : Shows which elements are Not a Number. isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. NaN and NAN are aliases of nan. Examples >>> np.nan nan >>> np.log(-1) nan >>> np.log([-1, 1, 2]) array([ NaN, 0. , 0.69314718]) numpy.newaxis A convenient alias for None, useful for indexing arrays. Examples >>> newaxis is None True >>> x = np.arange(3) >>> x array([0, 1, 2]) >>> x[:, newaxis] array([[0], [1], [2]]) >>> x[:, newaxis, newaxis] array([[[0]], [[1]], [[2]]]) >>> x[:, newaxis] * x array([[0, 0, 0], [0, 1, 2], [0, 2, 4]]) Outer product, same as outer(x, y): >>> y = np.arange(3, 6) >>> x[:, newaxis] * y array([[ 0, 0, 0], [ 3, 4, 5], [ 6, 8, 10]]) x[newaxis, :] is equivalent to x[newaxis] and x[None]: >>> x[newaxis, :].shape (1, 3) >>> x[newaxis].shape (1, 3) >>> x[None].shape (1, 3) >>> x[:, newaxis].shape (3, 1) numpy.pi pi = 3.1415926535897932384626433... References https://en.wikipedia.org/wiki/Pi
numpy.reference.constants
numpy.inf IEEE 754 floating point representation of (positive) infinity. Returns yfloat A floating point representation of positive infinity. See Also isinf : Shows which elements are positive or negative infinity isposinf : Shows which elements are positive infinity isneginf : Shows which elements are negative infinity isnan : Shows which elements are Not a Number isfinite : Shows which elements are finite (not one of Not a Number, positive infinity and negative infinity) Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity is equivalent to positive infinity. Inf, Infinity, PINF and infty are aliases for inf. Examples >>> np.inf inf >>> np.array([1]) / 0. array([ Inf])
numpy.reference.constants#numpy.inf
numpy.Infinity IEEE 754 floating point representation of (positive) infinity. Use inf because Inf, Infinity, PINF and infty are aliases for inf. For more details, see inf. See Also inf
numpy.reference.constants#numpy.Infinity
numpy.info numpy.info(object=None, maxwidth=76, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, toplevel='numpy')[source] Get help information for a function, class, or module. Parameters objectobject or str, optional Input object or name to get information about. If object is a numpy object, its docstring is given. If it is a string, available modules are searched for matching objects. If None, information about info itself is returned. maxwidthint, optional Printing width. outputfile like object, optional File like object that the output is written to, default is stdout. The object has to be opened in ‘w’ or ‘a’ mode. toplevelstr, optional Start search at this level. See also source, lookfor Notes When used interactively with an object, np.info(obj) is equivalent to help(obj) on the Python prompt or obj? on the IPython prompt. Examples >>> np.info(np.polyval) polyval(p, x) Evaluate the polynomial p at x. ... When using a string for object it is possible to get multiple results. >>> np.info('fft') *** Found in numpy *** Core FFT routines ... *** Found in numpy.fft *** fft(a, n=None, axis=-1) ... *** Repeat reference found in numpy.fft.fftpack *** *** Total of 3 references found. ***
numpy.reference.generated.numpy.info
numpy.infty IEEE 754 floating point representation of (positive) infinity. Use inf because Inf, Infinity, PINF and infty are aliases for inf. For more details, see inf. See Also inf
numpy.reference.constants#numpy.infty
numpy.inner numpy.inner(a, b, /) Inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes. Parameters a, barray_like If a and b are nonscalar, their last dimensions must match. Returns outndarray If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. out.shape = (*a.shape[:-1], *b.shape[:-1]) Raises ValueError If both a and b are nonscalar and their last dimensions have different sizes. See also tensordot Sum products over arbitrary axes. dot Generalised matrix product, using second last dimension of b. einsum Einstein summation convention. Notes For vectors (1-D arrays) it computes the ordinary inner-product: np.inner(a, b) = sum(a[:]*b[:]) More generally, if ndim(a) = r > 0 and ndim(b) = s > 0: np.inner(a, b) = np.tensordot(a, b, axes=(-1,-1)) or explicitly: np.inner(a, b)[i0,...,ir-2,j0,...,js-2] = sum(a[i0,...,ir-2,:]*b[j0,...,js-2,:]) In addition a or b may be scalars, in which case: np.inner(a,b) = a*b Examples Ordinary inner product for vectors: >>> a = np.array([1,2,3]) >>> b = np.array([0,1,0]) >>> np.inner(a, b) 2 Some multidimensional examples: >>> a = np.arange(24).reshape((2,3,4)) >>> b = np.arange(4) >>> c = np.inner(a, b) >>> c.shape (2, 3) >>> c array([[ 14, 38, 62], [ 86, 110, 134]]) >>> a = np.arange(2).reshape((1,1,2)) >>> b = np.arange(6).reshape((3,2)) >>> c = np.inner(a, b) >>> c.shape (1, 1, 3) >>> c array([[[1, 3, 5]]]) An example where b is a scalar: >>> np.inner(np.eye(2), 7) array([[7., 0.], [0., 7.]])
numpy.reference.generated.numpy.inner
numpy.insert numpy.insert(arr, obj, values, axis=None)[source] Insert values along the given axis before the given indices. Parameters arrarray_like Input array. objint, slice or sequence of ints Object that defines the index or indices before which values is inserted. New in version 1.8.0. Support for multiple insertions when obj is a single scalar or a sequence with one element (similar to calling insert multiple times). valuesarray_like Values to insert into arr. If the type of values is different from that of arr, values is converted to the type of arr. values should be shaped so that arr[...,obj,...] = values is legal. axisint, optional Axis along which to insert values. If axis is None then arr is flattened first. Returns outndarray A copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned. If axis is None, out is a flattened array. See also append Append elements at the end of an array. concatenate Join a sequence of arrays along an existing axis. delete Delete elements from an array. Notes Note that for higher dimensional inserts obj=0 behaves very different from obj=[0] just like arr[:,0,:] = values is different from arr[:,[0],:] = values. Examples >>> a = np.array([[1, 1], [2, 2], [3, 3]]) >>> a array([[1, 1], [2, 2], [3, 3]]) >>> np.insert(a, 1, 5) array([1, 5, 1, ..., 2, 3, 3]) >>> np.insert(a, 1, 5, axis=1) array([[1, 5, 1], [2, 5, 2], [3, 5, 3]]) Difference between sequence and scalars: >>> np.insert(a, [1], [[1],[2],[3]], axis=1) array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1), ... np.insert(a, [1], [[1],[2],[3]], axis=1)) True >>> b = a.flatten() >>> b array([1, 1, 2, 2, 3, 3]) >>> np.insert(b, [2, 2], [5, 6]) array([1, 1, 5, ..., 2, 3, 3]) >>> np.insert(b, slice(2, 4), [5, 6]) array([1, 1, 5, ..., 2, 3, 3]) >>> np.insert(b, [2, 2], [7.13, False]) # type casting array([1, 1, 7, ..., 2, 3, 3]) >>> x = np.arange(8).reshape(2, 4) >>> idx = (1, 3) >>> np.insert(x, idx, 999, axis=1) array([[ 0, 999, 1, 2, 999, 3], [ 4, 999, 5, 6, 999, 7]])
numpy.reference.generated.numpy.insert
numpy.int8[source] numpy.int16 numpy.int32 numpy.int64 Aliases for the signed integer types (one of numpy.byte, numpy.short, numpy.intc, numpy.int_ and numpy.longlong) with the specified number of bits. Compatible with the C99 int8_t, int16_t, int32_t, and int64_t, respectively.
numpy.reference.arrays.scalars#numpy.int16
numpy.int8[source] numpy.int16 numpy.int32 numpy.int64 Aliases for the signed integer types (one of numpy.byte, numpy.short, numpy.intc, numpy.int_ and numpy.longlong) with the specified number of bits. Compatible with the C99 int8_t, int16_t, int32_t, and int64_t, respectively.
numpy.reference.arrays.scalars#numpy.int32
numpy.int8[source] numpy.int16 numpy.int32 numpy.int64 Aliases for the signed integer types (one of numpy.byte, numpy.short, numpy.intc, numpy.int_ and numpy.longlong) with the specified number of bits. Compatible with the C99 int8_t, int16_t, int32_t, and int64_t, respectively.
numpy.reference.arrays.scalars#numpy.int64
numpy.int8[source] numpy.int16 numpy.int32 numpy.int64 Aliases for the signed integer types (one of numpy.byte, numpy.short, numpy.intc, numpy.int_ and numpy.longlong) with the specified number of bits. Compatible with the C99 int8_t, int16_t, int32_t, and int64_t, respectively.
numpy.reference.arrays.scalars#numpy.int8
class numpy.int_[source] Signed integer type, compatible with Python int and C long. Character code 'l' Alias on this platform (Linux x86_64) numpy.int64: 64-bit signed integer (-9_223_372_036_854_775_808 to 9_223_372_036_854_775_807). Alias on this platform (Linux x86_64) numpy.intp: Signed integer large enough to fit pointer, compatible with C intptr_t.
numpy.reference.arrays.scalars#numpy.int_
class numpy.intc[source] Signed integer type, compatible with C int. Character code 'i' Alias on this platform (Linux x86_64) numpy.int32: 32-bit signed integer (-2_147_483_648 to 2_147_483_647).
numpy.reference.arrays.scalars#numpy.intc
numpy.interp numpy.interp(x, xp, fp, left=None, right=None, period=None)[source] One-dimensional linear interpolation for monotonically increasing sample points. Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x. Parameters xarray_like The x-coordinates at which to evaluate the interpolated values. xp1-D sequence of floats The x-coordinates of the data points, must be increasing if argument period is not specified. Otherwise, xp is internally sorted after normalizing the periodic boundaries with xp = xp % period. fp1-D sequence of float or complex The y-coordinates of the data points, same length as xp. leftoptional float or complex corresponding to fp Value to return for x < xp[0], default is fp[0]. rightoptional float or complex corresponding to fp Value to return for x > xp[-1], default is fp[-1]. periodNone or float, optional A period for the x-coordinates. This parameter allows the proper interpolation of angular x-coordinates. Parameters left and right are ignored if period is specified. New in version 1.10.0. Returns yfloat or complex (corresponding to fp) or ndarray The interpolated values, same shape as x. Raises ValueError If xp and fp have different length If xp or fp are not 1-D sequences If period == 0 Warning The x-coordinate sequence is expected to be increasing, but this is not explicitly enforced. However, if the sequence xp is non-increasing, interpolation results are meaningless. Note that, since NaN is unsortable, xp also cannot contain NaNs. A simple check for xp being strictly increasing is: np.all(np.diff(xp) > 0) See also scipy.interpolate Examples >>> xp = [1, 2, 3] >>> fp = [3, 2, 0] >>> np.interp(2.5, xp, fp) 1.0 >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp) array([3. , 3. , 2.5 , 0.56, 0. ]) >>> UNDEF = -99.0 >>> np.interp(3.14, xp, fp, right=UNDEF) -99.0 Plot an interpolant to the sine function: >>> x = np.linspace(0, 2*np.pi, 10) >>> y = np.sin(x) >>> xvals = np.linspace(0, 2*np.pi, 50) >>> yinterp = np.interp(xvals, x, y) >>> import matplotlib.pyplot as plt >>> plt.plot(x, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(xvals, yinterp, '-x') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.show() Interpolation with periodic x-coordinates: >>> x = [-180, -170, -185, 185, -10, -5, 0, 365] >>> xp = [190, -190, 350, -350] >>> fp = [5, 10, 3, 4] >>> np.interp(x, xp, fp, period=360) array([7.5 , 5. , 8.75, 6.25, 3. , 3.25, 3.5 , 3.75]) Complex interpolation: >>> x = [1.5, 4.0] >>> xp = [2,3,5] >>> fp = [1.0j, 0, 2+3j] >>> np.interp(x, xp, fp) array([0.+1.j , 1.+1.5j])
numpy.reference.generated.numpy.interp
numpy.intersect1d numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)[source] Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ar1, ar2array_like Input arrays. Will be flattened if not already 1D. assume_uniquebool If True, the input arrays are both assumed to be unique, which can speed up the calculation. If True but ar1 or ar2 are not unique, incorrect results and out-of-bounds indices could result. Default is False. return_indicesbool If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False. New in version 1.15.0. Returns intersect1dndarray Sorted 1D array of common and unique elements. comm1ndarray The indices of the first occurrences of the common values in ar1. Only provided if return_indices is True. comm2ndarray The indices of the first occurrences of the common values in ar2. Only provided if return_indices is True. See also numpy.lib.arraysetops Module with a number of other functions for performing set operations on arrays. Examples >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1]) array([1, 3]) To intersect more than two arrays, use functools.reduce: >>> from functools import reduce >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2])) array([3]) To return the indices of the values common to the input arrays along with the intersected values: >>> x = np.array([1, 1, 2, 3, 4]) >>> y = np.array([2, 1, 4, 6]) >>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True) >>> x_ind, y_ind (array([0, 2, 4]), array([1, 0, 2])) >>> xy, x[x_ind], y[y_ind] (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
numpy.reference.generated.numpy.intersect1d
numpy.intp[source] Alias for the signed integer type (one of numpy.byte, numpy.short, numpy.intc, numpy.int_ and np.longlong) that is the same size as a pointer. Compatible with the C intptr_t. Character code 'p'
numpy.reference.arrays.scalars#numpy.intp
numpy.invert numpy.invert(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'invert'> Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~. For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value. This is the most common method of representing signed integers on computers [1]. A N-bit two’s-complement system can represent every integer in the range \(-2^{N-1}\) to \(+2^{N-1}-1\). Parameters xarray_like Only integer and boolean types are handled. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns outndarray or scalar Result. This is a scalar if x is a scalar. See also bitwise_and, bitwise_or, bitwise_xor logical_not binary_repr Return the binary representation of the input number as a string. Notes bitwise_not is an alias for invert: >>> np.bitwise_not is np.invert True References 1 Wikipedia, “Two’s complement”, https://en.wikipedia.org/wiki/Two’s_complement Examples We’ve seen that 13 is represented by 00001101. The invert or bit-wise NOT of 13 is then: >>> x = np.invert(np.array(13, dtype=np.uint8)) >>> x 242 >>> np.binary_repr(x, width=8) '11110010' The result depends on the bit-width: >>> x = np.invert(np.array(13, dtype=np.uint16)) >>> x 65522 >>> np.binary_repr(x, width=16) '1111111111110010' When using signed integer types the result is the two’s complement of the result for the unsigned type: >>> np.invert(np.array([13], dtype=np.int8)) array([-14], dtype=int8) >>> np.binary_repr(-14, width=8) '11110010' Booleans are accepted as well: >>> np.invert(np.array([True, False])) array([False, True]) The ~ operator can be used as a shorthand for np.invert on ndarrays. >>> x1 = np.array([True, False]) >>> ~x1 array([False, True])
numpy.reference.generated.numpy.invert
numpy.is_busday numpy.is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None) Calculates which of the given dates are valid days, and which are not. New in version 1.7.0. Parameters datesarray_like of datetime64[D] The array of dates to process. weekmaskstr or array_like of bool, optional A seven-element array indicating which of Monday through Sunday are valid days. May be specified as a length-seven list or array, like [1,1,1,1,1,0,0]; a length-seven string, like ‘1111100’; or a string like “Mon Tue Wed Thu Fri”, made up of 3-character abbreviations for weekdays, optionally separated by white space. Valid abbreviations are: Mon Tue Wed Thu Fri Sat Sun holidaysarray_like of datetime64[D], optional An array of dates to consider as invalid dates. They may be specified in any order, and NaT (not-a-time) dates are ignored. This list is saved in a normalized form that is suited for fast calculations of valid days. busdaycalbusdaycalendar, optional A busdaycalendar object which specifies the valid days. If this parameter is provided, neither weekmask nor holidays may be provided. outarray of bool, optional If provided, this array is filled with the result. Returns outarray of bool An array with the same shape as dates, containing True for each valid day, and False for each invalid day. See also busdaycalendar An object that specifies a custom set of valid days. busday_offset Applies an offset counted in valid days. busday_count Counts how many valid days are in a half-open date range. Examples >>> # The weekdays are Friday, Saturday, and Monday ... np.is_busday(['2011-07-01', '2011-07-02', '2011-07-18'], ... holidays=['2011-07-01', '2011-07-04', '2011-07-17']) array([False, False, True])
numpy.reference.generated.numpy.is_busday
numpy.isclose numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)[source] Returns a boolean array where two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b. Warning The default atol is not appropriate for comparing numbers that are much smaller than one (see Notes). Parameters a, barray_like Input arrays to compare. rtolfloat The relative tolerance parameter (see Notes). atolfloat The absolute tolerance parameter (see Notes). equal_nanbool Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array. Returns yarray_like Returns a boolean array of where a and b are equal within the given tolerance. If both a and b are scalars, returns a single boolean value. See also allclose math.isclose Notes New in version 1.7.0. For finite values, isclose uses the following equation to test whether two floating point values are equivalent. absolute(a - b) <= (atol + rtol * absolute(b)) Unlike the built-in math.isclose, the above equation is not symmetric in a and b – it assumes b is the reference value – so that isclose(a, b) might be different from isclose(b, a). Furthermore, the default value of atol is not zero, and is used to determine what small values should be considered close to zero. The default value is appropriate for expected values of order unity: if the expected values are significantly smaller than one, it can result in false positives. atol should be carefully selected for the use case at hand. A zero value for atol will result in False if either a or b is zero. isclose is not defined for non-numeric data types. bool is considered a numeric data-type for this purpose. Examples >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8]) array([ True, False]) >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9]) array([ True, True]) >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9]) array([False, True]) >>> np.isclose([1.0, np.nan], [1.0, np.nan]) array([ True, False]) >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True) array([ True, True]) >>> np.isclose([1e-8, 1e-7], [0.0, 0.0]) array([ True, False]) >>> np.isclose([1e-100, 1e-7], [0.0, 0.0], atol=0.0) array([False, False]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.0]) array([ True, True]) >>> np.isclose([1e-10, 1e-10], [1e-20, 0.999999e-10], atol=0.0) array([False, True])
numpy.reference.generated.numpy.isclose
numpy.iscomplex numpy.iscomplex(x)[source] Returns a bool array, where True if input element is complex. What is tested is whether the input has a non-zero imaginary part, not if the input type is complex. Parameters xarray_like Input array. Returns outndarray of bools Output array. See also isreal iscomplexobj Return True if x is a complex type or an array of complex numbers. Examples >>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j]) array([ True, False, False, False, False, True])
numpy.reference.generated.numpy.iscomplex
numpy.iscomplexobj numpy.iscomplexobj(x)[source] Check for a complex type or an array of complex numbers. The type of the input is checked, not the value. Even if the input has an imaginary part equal to zero, iscomplexobj evaluates to True. Parameters xany The input can be of any type and shape. Returns iscomplexobjbool The return value, True if x is of a complex type or has at least one complex element. See also isrealobj, iscomplex Examples >>> np.iscomplexobj(1) False >>> np.iscomplexobj(1+0j) True >>> np.iscomplexobj([3, 1+0j, True]) True
numpy.reference.generated.numpy.iscomplexobj
numpy.isfinite numpy.isfinite(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'isfinite'> Test element-wise for finiteness (not infinity and not Not a Number). The result is returned as a boolean array. 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, bool True where x is not positive infinity, negative infinity, or NaN; false otherwise. This is a scalar if x is a scalar. See also isinf, isneginf, isposinf, isnan Notes Not a Number, positive infinity and negative infinity are considered to be non-finite. NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity is equivalent to positive infinity. Errors result if the second argument is also supplied when x is a scalar input, or if first and second arguments have different shapes. Examples >>> np.isfinite(1) True >>> np.isfinite(0) True >>> np.isfinite(np.nan) False >>> np.isfinite(np.inf) False >>> np.isfinite(np.NINF) False >>> np.isfinite([np.log(-1.),1.,np.log(0)]) array([False, True, False]) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isfinite(x, y) array([0, 1, 0]) >>> y array([0, 1, 0])
numpy.reference.generated.numpy.isfinite
numpy.isfortran numpy.isfortran(a)[source] Check if the array is Fortran contiguous but not C contiguous. This function is obsolete and, because of changes due to relaxed stride checking, its return value for the same array may differ for versions of NumPy >= 1.10.0 and previous versions. If you only want to check if an array is Fortran contiguous use a.flags.f_contiguous instead. Parameters andarray Input array. Returns isfortranbool Returns True if the array is Fortran contiguous but not C contiguous. Examples np.array allows to specify whether the array is written in C-contiguous order (last index varies the fastest), or FORTRAN-contiguous order in memory (first index varies the fastest). >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False >>> b = np.array([[1, 2, 3], [4, 5, 6]], order='F') >>> b array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(b) True The transpose of a C-ordered array is a FORTRAN-ordered array. >>> a = np.array([[1, 2, 3], [4, 5, 6]], order='C') >>> a array([[1, 2, 3], [4, 5, 6]]) >>> np.isfortran(a) False >>> b = a.T >>> b array([[1, 4], [2, 5], [3, 6]]) >>> np.isfortran(b) True C-ordered arrays evaluate as False even if they are also FORTRAN-ordered. >>> np.isfortran(np.array([1, 2], order='F')) False
numpy.reference.generated.numpy.isfortran
numpy.isin numpy.isin(element, test_elements, assume_unique=False, invert=False)[source] Calculates element in test_elements, broadcasting over element only. Returns a boolean array of the same shape as element that is True where an element of element is in test_elements and False otherwise. Parameters elementarray_like Input array. test_elementsarray_like The values against which to test each value of element. This argument is flattened if it is an array or array_like. See notes for behavior with non-array-like parameters. assume_uniquebool, optional If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. invertbool, optional If True, the values in the returned array are inverted, as if calculating element not in test_elements. Default is False. np.isin(a, b, invert=True) is equivalent to (but faster than) np.invert(np.isin(a, b)). Returns isinndarray, bool Has the same shape as element. The values element[isin] are in test_elements. See also in1d Flattened version of this function. numpy.lib.arraysetops Module with a number of other functions for performing set operations on arrays. Notes isin is an element-wise function version of the python keyword in. isin(a, b) is roughly equivalent to np.array([item in b for item in a]) if a and b are 1-D sequences. element and test_elements are converted to arrays if they are not already. If test_elements is a set (or other non-sequence collection) it will be converted to an object array with one element, rather than an array of the values contained in test_elements. This is a consequence of the array constructor’s way of handling non-sequence collections. Converting the set to a list usually gives the desired behavior. New in version 1.13.0. Examples >>> element = 2*np.arange(4).reshape((2, 2)) >>> element array([[0, 2], [4, 6]]) >>> test_elements = [1, 2, 4, 8] >>> mask = np.isin(element, test_elements) >>> mask array([[False, True], [ True, False]]) >>> element[mask] array([2, 4]) The indices of the matched values can be obtained with nonzero: >>> np.nonzero(mask) (array([0, 1]), array([1, 0])) The test can also be inverted: >>> mask = np.isin(element, test_elements, invert=True) >>> mask array([[ True, False], [False, True]]) >>> element[mask] array([0, 6]) Because of how array handles sets, the following does not work as expected: >>> test_set = {1, 2, 4, 8} >>> np.isin(element, test_set) array([[False, False], [False, False]]) Casting the set to a list gives the expected result: >>> np.isin(element, list(test_set)) array([[False, True], [ True, False]])
numpy.reference.generated.numpy.isin
numpy.isinf numpy.isinf(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'isinf'> Test element-wise for positive or negative infinity. Returns a boolean array of the same shape as x, True where x == +/-inf, otherwise False. 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 ybool (scalar) or boolean ndarray True where x is positive or negative infinity, false otherwise. This is a scalar if x is a scalar. See also isneginf, isposinf, isnan, isfinite Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Errors result if the second argument is supplied when the first argument is a scalar, or if the first and second arguments have different shapes. Examples >>> np.isinf(np.inf) True >>> np.isinf(np.nan) False >>> np.isinf(np.NINF) True >>> np.isinf([np.inf, -np.inf, 1.0, np.nan]) array([ True, True, False, False]) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isinf(x, y) array([1, 0, 1]) >>> y array([1, 0, 1])
numpy.reference.generated.numpy.isinf
numpy.isnan numpy.isnan(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'isnan'> Test element-wise for NaN and return result as a boolean array. 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 or bool True where x is NaN, false otherwise. This is a scalar if x is a scalar. See also isinf, isneginf, isposinf, isfinite, isnat Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples >>> np.isnan(np.nan) True >>> np.isnan(np.inf) False >>> np.isnan([np.log(-1.),1.,np.log(0)]) array([ True, False, False])
numpy.reference.generated.numpy.isnan
numpy.isnat numpy.isnat(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'isnat'> Test element-wise for NaT (not a time) and return result as a boolean array. New in version 1.13.0. Parameters xarray_like Input array with datetime or timedelta data type. 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 bool True where x is NaT, false otherwise. This is a scalar if x is a scalar. See also isnan, isinf, isneginf, isposinf, isfinite Examples >>> np.isnat(np.datetime64("NaT")) True >>> np.isnat(np.datetime64("2016-01-01")) False >>> np.isnat(np.array(["NaT", "2016-01-01"], dtype="datetime64[ns]")) array([ True, False])
numpy.reference.generated.numpy.isnat
numpy.isneginf numpy.isneginf(x, out=None)[source] Test element-wise for negative infinity, return result as bool array. Parameters xarray_like The input array. outarray_like, optional A location into which the result is stored. If provided, it must have a shape that the input broadcasts to. If not provided or None, a freshly-allocated boolean array is returned. Returns outndarray A boolean array with the same dimensions as the input. If second argument is not supplied then a numpy boolean array is returned with values True where the corresponding element of the input is negative infinity and values False where the element of the input is not negative infinity. If a second argument is supplied the result is stored there. If the type of that array is a numeric type the result is represented as zeros and ones, if the type is boolean then as False and True. The return value out is then a reference to that array. See also isinf, isposinf, isnan, isfinite Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Errors result if the second argument is also supplied when x is a scalar input, if first and second arguments have different shapes, or if the first argument has complex values. Examples >>> np.isneginf(np.NINF) True >>> np.isneginf(np.inf) False >>> np.isneginf(np.PINF) False >>> np.isneginf([-np.inf, 0., np.inf]) array([ True, False, False]) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isneginf(x, y) array([1, 0, 0]) >>> y array([1, 0, 0])
numpy.reference.generated.numpy.isneginf
numpy.isposinf numpy.isposinf(x, out=None)[source] Test element-wise for positive infinity, return result as bool array. Parameters xarray_like The input array. outarray_like, optional A location into which the result is stored. If provided, it must have a shape that the input broadcasts to. If not provided or None, a freshly-allocated boolean array is returned. Returns outndarray A boolean array with the same dimensions as the input. If second argument is not supplied then a boolean array is returned with values True where the corresponding element of the input is positive infinity and values False where the element of the input is not positive infinity. If a second argument is supplied the result is stored there. If the type of that array is a numeric type the result is represented as zeros and ones, if the type is boolean then as False and True. The return value out is then a reference to that array. See also isinf, isneginf, isfinite, isnan Notes NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). Errors result if the second argument is also supplied when x is a scalar input, if first and second arguments have different shapes, or if the first argument has complex values Examples >>> np.isposinf(np.PINF) True >>> np.isposinf(np.inf) True >>> np.isposinf(np.NINF) False >>> np.isposinf([-np.inf, 0., np.inf]) array([False, False, True]) >>> x = np.array([-np.inf, 0., np.inf]) >>> y = np.array([2, 2, 2]) >>> np.isposinf(x, y) array([0, 0, 1]) >>> y array([0, 0, 1])
numpy.reference.generated.numpy.isposinf
numpy.isreal numpy.isreal(x)[source] Returns a bool array, where True if input element is real. If element has complex type with zero complex part, the return value for that element is True. Parameters xarray_like Input array. Returns outndarray, bool Boolean array of same shape as x. See also iscomplex isrealobj Return True if x is not a complex type. Notes isreal may behave unexpectedly for string or object arrays (see examples) Examples >>> a = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j], dtype=complex) >>> np.isreal(a) array([False, True, True, True, True, False]) The function does not work on string arrays. >>> a = np.array([2j, "a"], dtype="U") >>> np.isreal(a) # Warns about non-elementwise comparison False Returns True for all elements in input array of dtype=object even if any of the elements is complex. >>> a = np.array([1, "2", 3+4j], dtype=object) >>> np.isreal(a) array([ True, True, True]) isreal should not be used with object arrays >>> a = np.array([1+2j, 2+1j], dtype=object) >>> np.isreal(a) array([ True, True])
numpy.reference.generated.numpy.isreal
numpy.isrealobj numpy.isrealobj(x)[source] Return True if x is a not complex type or an array of complex numbers. The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, isrealobj evaluates to False if the data type is complex. Parameters xany The input can be of any type and shape. Returns ybool The return value, False if x is of a complex type. See also iscomplexobj, isreal Notes The function is only meant for arrays with numerical values but it accepts all other objects. Since it assumes array input, the return value of other objects may be True. >>> np.isrealobj('A string') True >>> np.isrealobj(False) True >>> np.isrealobj(None) True Examples >>> np.isrealobj(1) True >>> np.isrealobj(1+0j) False >>> np.isrealobj([3, 1+0j, True]) False
numpy.reference.generated.numpy.isrealobj
numpy.isscalar numpy.isscalar(element)[source] Returns True if the type of element is a scalar type. Parameters elementany Input argument, can be of any type and shape. Returns valbool True if element is a scalar type, False if it is not. See also ndim Get the number of dimensions of an array Notes If you need a stricter way to identify a numerical scalar, use isinstance(x, numbers.Number), as that returns False for most non-numerical elements such as strings. In most cases np.ndim(x) == 0 should be used instead of this function, as that will also return true for 0d arrays. This is how numpy overloads functions in the style of the dx arguments to gradient and the bins argument to histogram. Some key differences: x isscalar(x) np.ndim(x) == 0 PEP 3141 numeric objects (including builtins) True True builtin string and buffer objects True True other builtin objects, like pathlib.Path, Exception, the result of re.compile False True third-party objects like matplotlib.figure.Figure False True zero-dimensional numpy arrays False True other numpy arrays False False list, tuple, and other sequence objects False False Examples >>> np.isscalar(3.1) True >>> np.isscalar(np.array(3.1)) False >>> np.isscalar([3.1]) False >>> np.isscalar(False) True >>> np.isscalar('numpy') True NumPy supports PEP 3141 numbers: >>> from fractions import Fraction >>> np.isscalar(Fraction(5, 17)) True >>> from numbers import Number >>> np.isscalar(Number()) True
numpy.reference.generated.numpy.isscalar
numpy.issctype numpy.issctype(rep)[source] Determines whether the given object represents a scalar data-type. Parameters repany If rep is an instance of a scalar dtype, True is returned. If not, False is returned. Returns outbool Boolean result of check whether rep is a scalar dtype. See also issubsctype, issubdtype, obj2sctype, sctype2char Examples >>> np.issctype(np.int32) True >>> np.issctype(list) False >>> np.issctype(1.1) False Strings are also a scalar type: >>> np.issctype(np.dtype('str')) True
numpy.reference.generated.numpy.issctype
numpy.issubclass_ numpy.issubclass_(arg1, arg2)[source] Determine if a class is a subclass of a second class. issubclass_ is equivalent to the Python built-in issubclass, except that it returns False instead of raising a TypeError if one of the arguments is not a class. Parameters arg1class Input class. True is returned if arg1 is a subclass of arg2. arg2class or tuple of classes. Input class. If a tuple of classes, True is returned if arg1 is a subclass of any of the tuple elements. Returns outbool Whether arg1 is a subclass of arg2 or not. See also issubsctype, issubdtype, issctype Examples >>> np.issubclass_(np.int32, int) False >>> np.issubclass_(np.int32, float) False >>> np.issubclass_(np.float64, float) True
numpy.reference.generated.numpy.issubclass_
numpy.issubdtype numpy.issubdtype(arg1, arg2)[source] Returns True if first argument is a typecode lower/equal in type hierarchy. This is like the builtin issubclass, but for dtypes. Parameters arg1, arg2dtype_like dtype or object coercible to one Returns outbool See also Scalars Overview of the numpy type hierarchy. issubsctype, issubclass_ Examples issubdtype can be used to check the type of arrays: >>> ints = np.array([1, 2, 3], dtype=np.int32) >>> np.issubdtype(ints.dtype, np.integer) True >>> np.issubdtype(ints.dtype, np.floating) False >>> floats = np.array([1, 2, 3], dtype=np.float32) >>> np.issubdtype(floats.dtype, np.integer) False >>> np.issubdtype(floats.dtype, np.floating) True Similar types of different sizes are not subdtypes of each other: >>> np.issubdtype(np.float64, np.float32) False >>> np.issubdtype(np.float32, np.float64) False but both are subtypes of floating: >>> np.issubdtype(np.float64, np.floating) True >>> np.issubdtype(np.float32, np.floating) True For convenience, dtype-like objects are allowed too: >>> np.issubdtype('S1', np.string_) True >>> np.issubdtype('i4', np.signedinteger) True
numpy.reference.generated.numpy.issubdtype
numpy.issubsctype numpy.issubsctype(arg1, arg2)[source] Determine if the first argument is a subclass of the second argument. Parameters arg1, arg2dtype or dtype specifier Data-types. Returns outbool The result. See also issctype, issubdtype, obj2sctype Examples >>> np.issubsctype('S8', str) False >>> np.issubsctype(np.array([1]), int) True >>> np.issubsctype(np.array([1]), float) False
numpy.reference.generated.numpy.issubsctype
numpy.ix_ numpy.ix_(*args)[source] Construct an open mesh from multiple sequences. This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions. Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]]. Parameters args1-D sequences Each sequence should be of integer or boolean type. Boolean sequences will be interpreted as boolean masks for the corresponding dimension (equivalent to passing in np.nonzero(boolean_sequence)). Returns outtuple of ndarrays N arrays with N dimensions each, with N the number of input sequences. Together these arrays form an open mesh. See also ogrid, mgrid, meshgrid Examples >>> a = np.arange(10).reshape(2, 5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> ixgrid = np.ix_([0, 1], [2, 4]) >>> ixgrid (array([[0], [1]]), array([[2, 4]])) >>> ixgrid[0].shape, ixgrid[1].shape ((2, 1), (1, 2)) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [2, 4]) >>> a[ixgrid] array([[2, 4], [7, 9]]) >>> ixgrid = np.ix_([True, True], [False, False, True, False, True]) >>> a[ixgrid] array([[2, 4], [7, 9]])
numpy.reference.generated.numpy.ix_
numpy.kaiser numpy.kaiser(M, beta)[source] Return the Kaiser window. The Kaiser window is a taper formed by using a Bessel function. Parameters Mint Number of points in the output window. If zero or less, an empty array is returned. betafloat Shape parameter for window. Returns outarray The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd). See also bartlett, blackman, hamming, hanning Notes The Kaiser window is defined as \[w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}} \right)/I_0(\beta)\] with \[\quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},\] where \(I_0\) is the modified zeroth-order Bessel function. The Kaiser was named for Jim Kaiser, who discovered a simple approximation to the DPSS window based on Bessel functions. The Kaiser window is a very good approximation to the Digital Prolate Spheroidal Sequence, or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative to total energy. The Kaiser can approximate many other windows by varying the beta parameter. beta Window shape 0 Rectangular 5 Similar to a Hamming 6 Similar to a Hanning 8.6 Similar to a Blackman A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise NaNs will get returned. Most references to the Kaiser window come from the signal processing literature, where it is used as one of many windowing functions for smoothing values. It is also known as an apodization (which means “removing the foot”, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. References 1 J. F. Kaiser, “Digital Filters” - Ch 7 in “Systems analysis by digital computer”, Editors: F.F. Kuo and J.F. Kaiser, p 218-285. John Wiley and Sons, New York, (1966). 2 E.R. Kanasewich, “Time Sequence Analysis in Geophysics”, The University of Alberta Press, 1975, pp. 177-178. 3 Wikipedia, “Window function”, https://en.wikipedia.org/wiki/Window_function Examples >>> import matplotlib.pyplot as plt >>> np.kaiser(12, 14) array([7.72686684e-06, 3.46009194e-03, 4.65200189e-02, # may vary 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, 4.65200189e-02, 3.46009194e-03, 7.72686684e-06]) Plot the window and the frequency response: >>> from numpy.fft import fft, fftshift >>> window = np.kaiser(51, 14) >>> plt.plot(window) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Kaiser window") Text(0.5, 1.0, 'Kaiser window') >>> plt.ylabel("Amplitude") Text(0, 0.5, 'Amplitude') >>> plt.xlabel("Sample") Text(0.5, 0, 'Sample') >>> plt.show() >>> plt.figure() <Figure size 640x480 with 0 Axes> >>> A = fft(window, 2048) / 25.5 >>> mag = np.abs(fftshift(A)) >>> freq = np.linspace(-0.5, 0.5, len(A)) >>> response = 20 * np.log10(mag) >>> response = np.clip(response, -100, 100) >>> plt.plot(freq, response) [<matplotlib.lines.Line2D object at 0x...>] >>> plt.title("Frequency response of Kaiser window") Text(0.5, 1.0, 'Frequency response of Kaiser window') >>> plt.ylabel("Magnitude [dB]") Text(0, 0.5, 'Magnitude [dB]') >>> plt.xlabel("Normalized frequency [cycles per sample]") Text(0.5, 0, 'Normalized frequency [cycles per sample]') >>> plt.axis('tight') (-0.5, 0.5, -100.0, ...) # may vary >>> plt.show()
numpy.reference.generated.numpy.kaiser
numpy.kron numpy.kron(a, b)[source] Kronecker product of two arrays. Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first. Parameters a, barray_like Returns outndarray See also outer The outer product Notes The function assumes that the number of dimensions of a and b are the same, if necessary prepending the smallest with ones. If a.shape = (r0,r1,..,rN) and b.shape = (s0,s1,...,sN), the Kronecker product has shape (r0*s0, r1*s1, ..., rN*SN). The elements are products of elements from a and b, organized explicitly by: kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN] where: kt = it * st + jt, t = 0,...,N In the common 2-D case (N=1), the block structure can be visualized: [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ], [ ... ... ], [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]] Examples >>> np.kron([1,10,100], [5,6,7]) array([ 5, 6, 7, ..., 500, 600, 700]) >>> np.kron([5,6,7], [1,10,100]) array([ 5, 50, 500, ..., 7, 70, 700]) >>> np.kron(np.eye(2), np.ones((2,2))) array([[1., 1., 0., 0.], [1., 1., 0., 0.], [0., 0., 1., 1.], [0., 0., 1., 1.]]) >>> a = np.arange(100).reshape((2,5,2,5)) >>> b = np.arange(24).reshape((2,3,4)) >>> c = np.kron(a,b) >>> c.shape (2, 10, 6, 20) >>> I = (1,3,0,2) >>> J = (0,2,1) >>> J1 = (0,) + J # extend to ndim=4 >>> S1 = (1,) + b.shape >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1)) >>> c[K] == a[I]*b[J] True
numpy.reference.generated.numpy.kron
numpy.lcm numpy.lcm(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'lcm'> Returns the lowest common multiple of |x1| and |x2| Parameters x1, x2array_like, int Arrays of values. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). Returns yndarray or scalar The lowest common multiple of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars. See also gcd The greatest common divisor Examples >>> np.lcm(12, 20) 60 >>> np.lcm.reduce([3, 12, 20]) 60 >>> np.lcm.reduce([40, 12, 20]) 120 >>> np.lcm(np.arange(6), 20) array([ 0, 20, 20, 60, 20, 20])
numpy.reference.generated.numpy.lcm
numpy.ldexp numpy.ldexp(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'ldexp'> Returns x1 * 2**x2, element-wise. The mantissas x1 and twos exponents x2 are used to construct floating point numbers x1 * 2**x2. Parameters x1array_like Array of multipliers. x2array_like, int Array of twos exponents. 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 or scalar The result of x1 * 2**x2. This is a scalar if both x1 and x2 are scalars. See also frexp Return (y1, y2) from x = y1 * 2**y2, inverse to ldexp. Notes Complex dtypes are not supported, they will raise a TypeError. ldexp is useful as the inverse of frexp, if used by itself it is more clear to simply use the expression x1 * 2**x2. Examples >>> np.ldexp(5, np.arange(4)) array([ 5., 10., 20., 40.], dtype=float16) >>> x = np.arange(6) >>> np.ldexp(*np.frexp(x)) array([ 0., 1., 2., 3., 4., 5.])
numpy.reference.generated.numpy.ldexp
numpy.left_shift numpy.left_shift(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'left_shift'> Shift the bits of an integer to the left. Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying x1 by 2**x2. Parameters x1array_like of integer type Input values. x2array_like of integer type Number of zeros to append to x1. Has to be non-negative. 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 outarray of integer type Return x1 with bits shifted x2 times to the left. This is a scalar if both x1 and x2 are scalars. See also right_shift Shift the bits of an integer to the right. binary_repr Return the binary representation of the input number as a string. Examples >>> np.binary_repr(5) '101' >>> np.left_shift(5, 2) 20 >>> np.binary_repr(20) '10100' >>> np.left_shift(5, [1,2,3]) array([10, 20, 40]) Note that the dtype of the second argument may change the dtype of the result and can lead to unexpected results in some cases (see Casting Rules): >>> a = np.left_shift(np.uint8(255), 1) # Expect 254 >>> print(a, type(a)) # Unexpected result due to upcasting 510 <class 'numpy.int64'> >>> b = np.left_shift(np.uint8(255), np.uint8(1)) >>> print(b, type(b)) 254 <class 'numpy.uint8'> The << operator can be used as a shorthand for np.left_shift on ndarrays. >>> x1 = 5 >>> x2 = np.array([1, 2, 3]) >>> x1 << x2 array([10, 20, 40])
numpy.reference.generated.numpy.left_shift
numpy.less numpy.less(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'less'> Return the truth value of (x1 < x2) element-wise. Parameters x1, x2array_like Input arrays. 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 Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. See also greater, less_equal, greater_equal, equal, not_equal Examples >>> np.less([1, 2], [2, 2]) array([ True, False]) The < operator can be used as a shorthand for np.less on ndarrays. >>> a = np.array([1, 2]) >>> b = np.array([2, 2]) >>> a < b array([ True, False])
numpy.reference.generated.numpy.less
numpy.less_equal numpy.less_equal(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'less_equal'> Return the truth value of (x1 <= x2) element-wise. Parameters x1, x2array_like Input arrays. 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 Output array, element-wise comparison of x1 and x2. Typically of type bool, unless dtype=object is passed. This is a scalar if both x1 and x2 are scalars. See also greater, less, greater_equal, equal, not_equal Examples >>> np.less_equal([4, 2, 1], [2, 2, 2]) array([False, True, True]) The <= operator can be used as a shorthand for np.less_equal on ndarrays. >>> a = np.array([4, 2, 1]) >>> b = np.array([2, 2, 2]) >>> a <= b array([False, True, True])
numpy.reference.generated.numpy.less_equal
numpy.lexsort numpy.lexsort(keys, axis=- 1) Perform an indirect stable sort using a sequence of keys. Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys argument, its rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc. Parameters keys(k, N) array or tuple containing k (N,)-shaped sequences The k different “columns” to be sorted. The last column (or row if keys is a 2D array) is the primary sort key. axisint, optional Axis to be indirectly sorted. By default, sort over the last axis. Returns indices(N,) ndarray of ints Array of indices that sort the keys along the specified axis. See also argsort Indirect sort. ndarray.sort In-place sort. sort Return a sorted copy of an array. Examples Sort names: first by surname, then by name. >>> surnames = ('Hertz', 'Galilei', 'Hertz') >>> first_names = ('Heinrich', 'Galileo', 'Gustav') >>> ind = np.lexsort((first_names, surnames)) >>> ind array([1, 2, 0]) >>> [surnames[i] + ", " + first_names[i] for i in ind] ['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich'] Sort two columns of numbers: >>> a = [1,5,1,4,3,4,4] # First column >>> b = [9,4,0,4,0,2,1] # Second column >>> ind = np.lexsort((b,a)) # Sort by a, then by b >>> ind array([2, 0, 4, 6, 5, 3, 1]) >>> [(a[i],b[i]) for i in ind] [(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)] Note that sorting is first according to the elements of a. Secondary sorting is according to the elements of b. A normal argsort would have yielded: >>> [(a[i],b[i]) for i in np.argsort(a)] [(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)] Structured arrays are sorted lexically by argsort: >>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)], ... dtype=np.dtype([('x', int), ('y', int)])) >>> np.argsort(x) # or np.argsort(x, order=('x', 'y')) array([2, 0, 4, 6, 5, 3, 1])
numpy.reference.generated.numpy.lexsort
numpy.lib.arraysetops Set operations for arrays based on sorting. Notes For floating point arrays, inaccurate results may appear due to usual round-off and floating point comparison issues. Speed could be gained in some operations by an implementation of numpy.sort, that can provide directly the permutation vectors, thus avoiding calls to numpy.argsort. Original author: Robert Cimrman
numpy.reference.generated.numpy.lib.arraysetops
numpy.lib.Arrayterator class numpy.lib.Arrayterator(var, buf_size=None)[source] Buffered iterator for big arrays. Arrayterator creates a buffered iterator for reading big arrays in small contiguous blocks. The class is useful for objects stored in the file system. It allows iteration over the object without reading everything in memory; instead, small blocks are read and iterated over. Arrayterator can be used with any object that supports multidimensional slices. This includes NumPy arrays, but also variables from Scientific.IO.NetCDF or pynetcdf for example. Parameters vararray_like The object to iterate over. buf_sizeint, optional The buffer size. If buf_size is supplied, the maximum amount of data that will be read into memory is buf_size elements. Default is None, which will read as many element as possible into memory. See also ndenumerate Multidimensional array iterator. flatiter Flat array iterator. memmap Create a memory-map to an array stored in a binary file on disk. Notes The algorithm works by first finding a “running dimension”, along which the blocks will be extracted. Given an array of dimensions (d1, d2, ..., dn), e.g. if buf_size is smaller than d1, the first dimension will be used. If, on the other hand, d1 < buf_size < d1*d2 the second dimension will be used, and so on. Blocks are extracted along this dimension, and when the last block is returned the process continues from the next dimension, until all elements have been read. Examples >>> a = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6) >>> a_itor = np.lib.Arrayterator(a, 2) >>> a_itor.shape (3, 4, 5, 6) Now we can iterate over a_itor, and it will return arrays of size two. Since buf_size was smaller than any dimension, the first dimension will be iterated over first: >>> for subarr in a_itor: ... if not subarr.all(): ... print(subarr, subarr.shape) >>> # [[[[0 1]]]] (1, 1, 1, 2) Attributes var buf_size start stop step shape The shape of the array to be iterated over. flat A 1-D flat iterator for Arrayterator objects.
numpy.reference.generated.numpy.lib.arrayterator
numpy.lib.mixins.NDArrayOperatorsMixin class numpy.lib.mixins.NDArrayOperatorsMixin[source] Mixin defining all operator special methods using __array_ufunc__. This class implements the special methods for almost all of Python’s builtin operators defined in the operator module, including comparisons (==, >, etc.) and arithmetic (+, *, -, etc.), by deferring to the __array_ufunc__ method, which subclasses must implement. It is useful for writing classes that do not inherit from numpy.ndarray, but that should support arithmetic and numpy universal functions like arrays as described in A Mechanism for Overriding Ufuncs. As an trivial example, consider this implementation of an ArrayLike class that simply wraps a NumPy array and ensures that the result of any arithmetic operation is also an ArrayLike object: class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin): def __init__(self, value): self.value = np.asarray(value) # One might also consider adding the built-in list type to this # list, to support operations like np.add(array_like, list) _HANDLED_TYPES = (np.ndarray, numbers.Number) def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): out = kwargs.get('out', ()) for x in inputs + out: # Only support operations with instances of _HANDLED_TYPES. # Use ArrayLike instead of type(self) for isinstance to # allow subclasses that don't override __array_ufunc__ to # handle ArrayLike objects. if not isinstance(x, self._HANDLED_TYPES + (ArrayLike,)): return NotImplemented # Defer to the implementation of the ufunc on unwrapped values. inputs = tuple(x.value if isinstance(x, ArrayLike) else x for x in inputs) if out: kwargs['out'] = tuple( x.value if isinstance(x, ArrayLike) else x for x in out) result = getattr(ufunc, method)(*inputs, **kwargs) if type(result) is tuple: # multiple return values return tuple(type(self)(x) for x in result) elif method == 'at': # no return value return None else: # one return value return type(self)(result) def __repr__(self): return '%s(%r)' % (type(self).__name__, self.value) In interactions between ArrayLike objects and numbers or numpy arrays, the result is always another ArrayLike: >>> x = ArrayLike([1, 2, 3]) >>> x - 1 ArrayLike(array([0, 1, 2])) >>> 1 - x ArrayLike(array([ 0, -1, -2])) >>> np.arange(3) - x ArrayLike(array([-1, -1, -1])) >>> x - np.arange(3) ArrayLike(array([1, 1, 1])) Note that unlike numpy.ndarray, ArrayLike does not allow operations with arbitrary, unrecognized types. This ensures that interactions with ArrayLike preserve a well-defined casting hierarchy. New in version 1.13.
numpy.reference.generated.numpy.lib.mixins.ndarrayoperatorsmixin
numpy.lib.NumpyVersion class numpy.lib.NumpyVersion(vstring)[source] Parse and compare numpy version strings. NumPy has the following versioning scheme (numbers given are examples; they can be > 9 in principle): Released version: ‘1.8.0’, ‘1.8.1’, etc. Alpha: ‘1.8.0a1’, ‘1.8.0a2’, etc. Beta: ‘1.8.0b1’, ‘1.8.0b2’, etc. Release candidates: ‘1.8.0rc1’, ‘1.8.0rc2’, etc. Development versions: ‘1.8.0.dev-f1234afa’ (git commit hash appended) Development versions after a1: ‘1.8.0a1.dev-f1234afa’, ‘1.8.0b2.dev-f1234afa’, ‘1.8.1rc1.dev-f1234afa’, etc. Development versions (no git hash available): ‘1.8.0.dev-Unknown’ Comparing needs to be done against a valid version string or other NumpyVersion instance. Note that all development versions of the same (pre-)release compare equal. New in version 1.9.0. Parameters vstringstr NumPy version string (np.__version__). Examples >>> from numpy.lib import NumpyVersion >>> if NumpyVersion(np.__version__) < '1.7.0': ... print('skip') >>> # skip >>> NumpyVersion('1.7') # raises ValueError, add ".0" Traceback (most recent call last): ... ValueError: Not a valid numpy version string
numpy.reference.generated.numpy.lib.numpyversion
Structured arrays Introduction Structured arrays are ndarrays whose datatype is a composition of simpler datatypes organized as a sequence of named fields. For example, >>> x = np.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)], ... dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')]) >>> x array([('Rex', 9, 81.), ('Fido', 3, 27.)], dtype=[('name', 'U10'), ('age', '<i4'), ('weight', '<f4')]) Here x is a one-dimensional array of length two whose datatype is a structure with three fields: 1. A string of length 10 or less named ‘name’, 2. a 32-bit integer named ‘age’, and 3. a 32-bit float named ‘weight’. If you index x at position 1 you get a structure: >>> x[1] ('Fido', 3, 27.0) You can access and modify individual fields of a structured array by indexing with the field name: >>> x['age'] array([9, 3], dtype=int32) >>> x['age'] = 5 >>> x array([('Rex', 5, 81.), ('Fido', 5, 27.)], dtype=[('name', 'U10'), ('age', '<i4'), ('weight', '<f4')]) Structured datatypes are designed to be able to mimic ‘structs’ in the C language, and share a similar memory layout. They are meant for interfacing with C code and for low-level manipulation of structured buffers, for example for interpreting binary blobs. For these purposes they support specialized features such as subarrays, nested datatypes, and unions, and allow control over the memory layout of the structure. Users looking to manipulate tabular data, such as stored in csv files, may find other pydata projects more suitable, such as xarray, pandas, or DataArray. These provide a high-level interface for tabular data analysis and are better optimized for that use. For instance, the C-struct-like memory layout of structured arrays in numpy can lead to poor cache behavior in comparison. Structured Datatypes A structured datatype can be thought of as a sequence of bytes of a certain length (the structure’s itemsize) which is interpreted as a collection of fields. Each field has a name, a datatype, and a byte offset within the structure. The datatype of a field may be any numpy datatype including other structured datatypes, and it may also be a subarray data type which behaves like an ndarray of a specified shape. The offsets of the fields are arbitrary, and fields may even overlap. These offsets are usually determined automatically by numpy, but can also be specified. Structured Datatype Creation Structured datatypes may be created using the function numpy.dtype. There are 4 alternative forms of specification which vary in flexibility and conciseness. These are further documented in the Data Type Objects reference page, and in summary they are: A list of tuples, one tuple per field Each tuple has the form (fieldname, datatype, shape) where shape is optional. fieldname is a string (or tuple if titles are used, see Field Titles below), datatype may be any object convertible to a datatype, and shape is a tuple of integers specifying subarray shape. >>> np.dtype([('x', 'f4'), ('y', np.float32), ('z', 'f4', (2, 2))]) dtype([('x', '<f4'), ('y', '<f4'), ('z', '<f4', (2, 2))]) If fieldname is the empty string '', the field will be given a default name of the form f#, where # is the integer index of the field, counting from 0 from the left: >>> np.dtype([('x', 'f4'), ('', 'i4'), ('z', 'i8')]) dtype([('x', '<f4'), ('f1', '<i4'), ('z', '<i8')]) The byte offsets of the fields within the structure and the total structure itemsize are determined automatically. A string of comma-separated dtype specifications In this shorthand notation any of the string dtype specifications may be used in a string and separated by commas. The itemsize and byte offsets of the fields are determined automatically, and the field names are given the default names f0, f1, etc. >>> np.dtype('i8, f4, S3') dtype([('f0', '<i8'), ('f1', '<f4'), ('f2', 'S3')]) >>> np.dtype('3int8, float32, (2, 3)float64') dtype([('f0', 'i1', (3,)), ('f1', '<f4'), ('f2', '<f8', (2, 3))]) A dictionary of field parameter arrays This is the most flexible form of specification since it allows control over the byte-offsets of the fields and the itemsize of the structure. The dictionary has two required keys, ‘names’ and ‘formats’, and four optional keys, ‘offsets’, ‘itemsize’, ‘aligned’ and ‘titles’. The values for ‘names’ and ‘formats’ should respectively be a list of field names and a list of dtype specifications, of the same length. The optional ‘offsets’ value should be a list of integer byte-offsets, one for each field within the structure. If ‘offsets’ is not given the offsets are determined automatically. The optional ‘itemsize’ value should be an integer describing the total size in bytes of the dtype, which must be large enough to contain all the fields. >>> np.dtype({'names': ['col1', 'col2'], 'formats': ['i4', 'f4']}) dtype([('col1', '<i4'), ('col2', '<f4')]) >>> np.dtype({'names': ['col1', 'col2'], ... 'formats': ['i4', 'f4'], ... 'offsets': [0, 4], ... 'itemsize': 12}) dtype({'names': ['col1', 'col2'], 'formats': ['<i4', '<f4'], 'offsets': [0, 4], 'itemsize': 12}) Offsets may be chosen such that the fields overlap, though this will mean that assigning to one field may clobber any overlapping field’s data. As an exception, fields of numpy.object_ type cannot overlap with other fields, because of the risk of clobbering the internal object pointer and then dereferencing it. The optional ‘aligned’ value can be set to True to make the automatic offset computation use aligned offsets (see Automatic Byte Offsets and Alignment), as if the ‘align’ keyword argument of numpy.dtype had been set to True. The optional ‘titles’ value should be a list of titles of the same length as ‘names’, see Field Titles below. A dictionary of field names The use of this form of specification is discouraged, but documented here because older numpy code may use it. The keys of the dictionary are the field names and the values are tuples specifying type and offset: >>> np.dtype({'col1': ('i1', 0), 'col2': ('f4', 1)}) dtype([('col1', 'i1'), ('col2', '<f4')]) This form is discouraged because Python dictionaries do not preserve order in Python versions before Python 3.6, and the order of the fields in a structured dtype has meaning. Field Titles may be specified by using a 3-tuple, see below. Manipulating and Displaying Structured Datatypes The list of field names of a structured datatype can be found in the names attribute of the dtype object: >>> d = np.dtype([('x', 'i8'), ('y', 'f4')]) >>> d.names ('x', 'y') The field names may be modified by assigning to the names attribute using a sequence of strings of the same length. The dtype object also has a dictionary-like attribute, fields, whose keys are the field names (and Field Titles, see below) and whose values are tuples containing the dtype and byte offset of each field. >>> d.fields mappingproxy({'x': (dtype('int64'), 0), 'y': (dtype('float32'), 8)}) Both the names and fields attributes will equal None for unstructured arrays. The recommended way to test if a dtype is structured is with if dt.names is not None rather than if dt.names, to account for dtypes with 0 fields. The string representation of a structured datatype is shown in the “list of tuples” form if possible, otherwise numpy falls back to using the more general dictionary form. Automatic Byte Offsets and Alignment Numpy uses one of two methods to automatically determine the field byte offsets and the overall itemsize of a structured datatype, depending on whether align=True was specified as a keyword argument to numpy.dtype. By default (align=False), numpy will pack the fields together such that each field starts at the byte offset the previous field ended, and the fields are contiguous in memory. >>> def print_offsets(d): ... print("offsets:", [d.fields[name][1] for name in d.names]) ... print("itemsize:", d.itemsize) >>> print_offsets(np.dtype('u1, u1, i4, u1, i8, u2')) offsets: [0, 1, 2, 6, 7, 15] itemsize: 17 If align=True is set, numpy will pad the structure in the same way many C compilers would pad a C-struct. Aligned structures can give a performance improvement in some cases, at the cost of increased datatype size. Padding bytes are inserted between fields such that each field’s byte offset will be a multiple of that field’s alignment, which is usually equal to the field’s size in bytes for simple datatypes, see PyArray_Descr.alignment. The structure will also have trailing padding added so that its itemsize is a multiple of the largest field’s alignment. >>> print_offsets(np.dtype('u1, u1, i4, u1, i8, u2', align=True)) offsets: [0, 1, 4, 8, 16, 24] itemsize: 32 Note that although almost all modern C compilers pad in this way by default, padding in C structs is C-implementation-dependent so this memory layout is not guaranteed to exactly match that of a corresponding struct in a C program. Some work may be needed, either on the numpy side or the C side, to obtain exact correspondence. If offsets were specified using the optional offsets key in the dictionary-based dtype specification, setting align=True will check that each field’s offset is a multiple of its size and that the itemsize is a multiple of the largest field size, and raise an exception if not. If the offsets of the fields and itemsize of a structured array satisfy the alignment conditions, the array will have the ALIGNED flag set. A convenience function numpy.lib.recfunctions.repack_fields converts an aligned dtype or array to a packed one and vice versa. It takes either a dtype or structured ndarray as an argument, and returns a copy with fields re-packed, with or without padding bytes. Field Titles In addition to field names, fields may also have an associated title, an alternate name, which is sometimes used as an additional description or alias for the field. The title may be used to index an array, just like a field name. To add titles when using the list-of-tuples form of dtype specification, the field name may be specified as a tuple of two strings instead of a single string, which will be the field’s title and field name respectively. For example: >>> np.dtype([(('my title', 'name'), 'f4')]) dtype([(('my title', 'name'), '<f4')]) When using the first form of dictionary-based specification, the titles may be supplied as an extra 'titles' key as described above. When using the second (discouraged) dictionary-based specification, the title can be supplied by providing a 3-element tuple (datatype, offset, title) instead of the usual 2-element tuple: >>> np.dtype({'name': ('i4', 0, 'my title')}) dtype([(('my title', 'name'), '<i4')]) The dtype.fields dictionary will contain titles as keys, if any titles are used. This means effectively that a field with a title will be represented twice in the fields dictionary. The tuple values for these fields will also have a third element, the field title. Because of this, and because the names attribute preserves the field order while the fields attribute may not, it is recommended to iterate through the fields of a dtype using the names attribute of the dtype, which will not list titles, as in: >>> for name in d.names: ... print(d.fields[name][:2]) (dtype('int64'), 0) (dtype('float32'), 8) Union types Structured datatypes are implemented in numpy to have base type numpy.void by default, but it is possible to interpret other numpy types as structured types using the (base_dtype, dtype) form of dtype specification described in Data Type Objects. Here, base_dtype is the desired underlying dtype, and fields and flags will be copied from dtype. This dtype is similar to a ‘union’ in C. Indexing and Assignment to Structured arrays Assigning data to a Structured Array There are a number of ways to assign values to a structured array: Using python tuples, using scalar values, or using other structured arrays. Assignment from Python Native Types (Tuples) The simplest way to assign values to a structured array is using python tuples. Each assigned value should be a tuple of length equal to the number of fields in the array, and not a list or array as these will trigger numpy’s broadcasting rules. The tuple’s elements are assigned to the successive fields of the array, from left to right: >>> x = np.array([(1, 2, 3), (4, 5, 6)], dtype='i8, f4, f8') >>> x[1] = (7, 8, 9) >>> x array([(1, 2., 3.), (7, 8., 9.)], dtype=[('f0', '<i8'), ('f1', '<f4'), ('f2', '<f8')]) Assignment from Scalars A scalar assigned to a structured element will be assigned to all fields. This happens when a scalar is assigned to a structured array, or when an unstructured array is assigned to a structured array: >>> x = np.zeros(2, dtype='i8, f4, ?, S1') >>> x[:] = 3 >>> x array([(3, 3., True, b'3'), (3, 3., True, b'3')], dtype=[('f0', '<i8'), ('f1', '<f4'), ('f2', '?'), ('f3', 'S1')]) >>> x[:] = np.arange(2) >>> x array([(0, 0., False, b'0'), (1, 1., True, b'1')], dtype=[('f0', '<i8'), ('f1', '<f4'), ('f2', '?'), ('f3', 'S1')]) Structured arrays can also be assigned to unstructured arrays, but only if the structured datatype has just a single field: >>> twofield = np.zeros(2, dtype=[('A', 'i4'), ('B', 'i4')]) >>> onefield = np.zeros(2, dtype=[('A', 'i4')]) >>> nostruct = np.zeros(2, dtype='i4') >>> nostruct[:] = twofield Traceback (most recent call last): ... TypeError: Cannot cast array data from dtype([('A', '<i4'), ('B', '<i4')]) to dtype('int32') according to the rule 'unsafe' Assignment from other Structured Arrays Assignment between two structured arrays occurs as if the source elements had been converted to tuples and then assigned to the destination elements. That is, the first field of the source array is assigned to the first field of the destination array, and the second field likewise, and so on, regardless of field names. Structured arrays with a different number of fields cannot be assigned to each other. Bytes of the destination structure which are not included in any of the fields are unaffected. >>> a = np.zeros(3, dtype=[('a', 'i8'), ('b', 'f4'), ('c', 'S3')]) >>> b = np.ones(3, dtype=[('x', 'f4'), ('y', 'S3'), ('z', 'O')]) >>> b[:] = a >>> b array([(0., b'0.0', b''), (0., b'0.0', b''), (0., b'0.0', b'')], dtype=[('x', '<f4'), ('y', 'S3'), ('z', 'O')]) Assignment involving subarrays When assigning to fields which are subarrays, the assigned value will first be broadcast to the shape of the subarray. Indexing Structured Arrays Accessing Individual Fields Individual fields of a structured array may be accessed and modified by indexing the array with the field name. >>> x = np.array([(1, 2), (3, 4)], dtype=[('foo', 'i8'), ('bar', 'f4')]) >>> x['foo'] array([1, 3]) >>> x['foo'] = 10 >>> x array([(10, 2.), (10, 4.)], dtype=[('foo', '<i8'), ('bar', '<f4')]) The resulting array is a view into the original array. It shares the same memory locations and writing to the view will modify the original array. >>> y = x['bar'] >>> y[:] = 11 >>> x array([(10, 11.), (10, 11.)], dtype=[('foo', '<i8'), ('bar', '<f4')]) This view has the same dtype and itemsize as the indexed field, so it is typically a non-structured array, except in the case of nested structures. >>> y.dtype, y.shape, y.strides (dtype('float32'), (2,), (12,)) If the accessed field is a subarray, the dimensions of the subarray are appended to the shape of the result: >>> x = np.zeros((2, 2), dtype=[('a', np.int32), ('b', np.float64, (3, 3))]) >>> x['a'].shape (2, 2) >>> x['b'].shape (2, 2, 3, 3) Accessing Multiple Fields One can index and assign to a structured array with a multi-field index, where the index is a list of field names. Warning The behavior of multi-field indexes changed from Numpy 1.15 to Numpy 1.16. The result of indexing with a multi-field index is a view into the original array, as follows: >>> a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'i4'), ('c', 'f4')]) >>> a[['a', 'c']] array([(0, 0.), (0, 0.), (0, 0.)], dtype={'names':['a','c'], 'formats':['<i4','<f4'], 'offsets':[0,8], 'itemsize':12}) Assignment to the view modifies the original array. The view’s fields will be in the order they were indexed. Note that unlike for single-field indexing, the dtype of the view has the same itemsize as the original array, and has fields at the same offsets as in the original array, and unindexed fields are merely missing. Warning In Numpy 1.15, indexing an array with a multi-field index returned a copy of the result above, but with fields packed together in memory as if passed through numpy.lib.recfunctions.repack_fields. The new behavior as of Numpy 1.16 leads to extra “padding” bytes at the location of unindexed fields compared to 1.15. You will need to update any code which depends on the data having a “packed” layout. For instance code such as: >>> a[['a', 'c']].view('i8') # Fails in Numpy 1.16 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: When changing to a smaller dtype, its size must be a divisor of the size of original dtype will need to be changed. This code has raised a FutureWarning since Numpy 1.12, and similar code has raised FutureWarning since 1.7. In 1.16 a number of functions have been introduced in the numpy.lib.recfunctions module to help users account for this change. These are numpy.lib.recfunctions.repack_fields. numpy.lib.recfunctions.structured_to_unstructured, numpy.lib.recfunctions.unstructured_to_structured, numpy.lib.recfunctions.apply_along_fields, numpy.lib.recfunctions.assign_fields_by_name, and numpy.lib.recfunctions.require_fields. The function numpy.lib.recfunctions.repack_fields can always be used to reproduce the old behavior, as it will return a packed copy of the structured array. The code above, for example, can be replaced with: >>> from numpy.lib.recfunctions import repack_fields >>> repack_fields(a[['a', 'c']]).view('i8') # supported in 1.16 array([0, 0, 0]) Furthermore, numpy now provides a new function numpy.lib.recfunctions.structured_to_unstructured which is a safer and more efficient alternative for users who wish to convert structured arrays to unstructured arrays, as the view above is often indeded to do. This function allows safe conversion to an unstructured type taking into account padding, often avoids a copy, and also casts the datatypes as needed, unlike the view. Code such as: >>> b = np.zeros(3, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4')]) >>> b[['x', 'z']].view('f4') array([0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32) can be made safer by replacing with: >>> from numpy.lib.recfunctions import structured_to_unstructured >>> structured_to_unstructured(b[['x', 'z']]) array([0, 0, 0]) Assignment to an array with a multi-field index modifies the original array: >>> a[['a', 'c']] = (2, 3) >>> a array([(2, 0, 3.), (2, 0, 3.), (2, 0, 3.)], dtype=[('a', '<i4'), ('b', '<i4'), ('c', '<f4')]) This obeys the structured array assignment rules described above. For example, this means that one can swap the values of two fields using appropriate multi-field indexes: >>> a[['a', 'c']] = a[['c', 'a']] Indexing with an Integer to get a Structured Scalar Indexing a single element of a structured array (with an integer index) returns a structured scalar: >>> x = np.array([(1, 2., 3.)], dtype='i, f, f') >>> scalar = x[0] >>> scalar (1, 2., 3.) >>> type(scalar) <class 'numpy.void'> Unlike other numpy scalars, structured scalars are mutable and act like views into the original array, such that modifying the scalar will modify the original array. Structured scalars also support access and assignment by field name: >>> x = np.array([(1, 2), (3, 4)], dtype=[('foo', 'i8'), ('bar', 'f4')]) >>> s = x[0] >>> s['bar'] = 100 >>> x array([(1, 100.), (3, 4.)], dtype=[('foo', '<i8'), ('bar', '<f4')]) Similarly to tuples, structured scalars can also be indexed with an integer: >>> scalar = np.array([(1, 2., 3.)], dtype='i, f, f')[0] >>> scalar[0] 1 >>> scalar[1] = 4 Thus, tuples might be thought of as the native Python equivalent to numpy’s structured types, much like native python integers are the equivalent to numpy’s integer types. Structured scalars may be converted to a tuple by calling numpy.ndarray.item: >>> scalar.item(), type(scalar.item()) ((1, 4.0, 3.0), <class 'tuple'>) Viewing Structured Arrays Containing Objects In order to prevent clobbering object pointers in fields of object type, numpy currently does not allow views of structured arrays containing objects. Structure Comparison If the dtypes of two void structured arrays are equal, testing the equality of the arrays will result in a boolean array with the dimensions of the original arrays, with elements set to True where all fields of the corresponding structures are equal. Structured dtypes are equal if the field names, dtypes and titles are the same, ignoring endianness, and the fields are in the same order: >>> a = np.zeros(2, dtype=[('a', 'i4'), ('b', 'i4')]) >>> b = np.ones(2, dtype=[('a', 'i4'), ('b', 'i4')]) >>> a == b array([False, False]) Currently, if the dtypes of two void structured arrays are not equivalent the comparison fails, returning the scalar value False. This behavior is deprecated as of numpy 1.10 and will raise an error or perform elementwise comparison in the future. The < and > operators always return False when comparing void structured arrays, and arithmetic and bitwise operations are not supported. Record Arrays As an optional convenience numpy provides an ndarray subclass, numpy.recarray that allows access to fields of structured arrays by attribute instead of only by index. Record arrays use a special datatype, numpy.record, that allows field access by attribute on the structured scalars obtained from the array. The numpy.rec module provides functions for creating recarrays from various objects. Additional helper functions for creating and manipulating structured arrays can be found in numpy.lib.recfunctions. The simplest way to create a record array is with numpy.rec.array: >>> recordarr = np.rec.array([(1, 2., 'Hello'), (2, 3., "World")], ... dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')]) >>> recordarr.bar array([ 2., 3.], dtype=float32) >>> recordarr[1:2] rec.array([(2, 3., b'World')], dtype=[('foo', '<i4'), ('bar', '<f4'), ('baz', 'S10')]) >>> recordarr[1:2].foo array([2], dtype=int32) >>> recordarr.foo[1:2] array([2], dtype=int32) >>> recordarr[1].baz b'World' numpy.rec.array can convert a wide variety of arguments into record arrays, including structured arrays: >>> arr = np.array([(1, 2., 'Hello'), (2, 3., "World")], ... dtype=[('foo', 'i4'), ('bar', 'f4'), ('baz', 'S10')]) >>> recordarr = np.rec.array(arr) The numpy.rec module provides a number of other convenience functions for creating record arrays, see record array creation routines. A record array representation of a structured array can be obtained using the appropriate view: >>> arr = np.array([(1, 2., 'Hello'), (2, 3., "World")], ... dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'a10')]) >>> recordarr = arr.view(dtype=np.dtype((np.record, arr.dtype)), ... type=np.recarray) For convenience, viewing an ndarray as type numpy.recarray will automatically convert to numpy.record datatype, so the dtype can be left out of the view: >>> recordarr = arr.view(np.recarray) >>> recordarr.dtype dtype((numpy.record, [('foo', '<i4'), ('bar', '<f4'), ('baz', 'S10')])) To get back to a plain ndarray both the dtype and type must be reset. The following view does so, taking into account the unusual case that the recordarr was not a structured type: >>> arr2 = recordarr.view(recordarr.dtype.fields or recordarr.dtype, np.ndarray) Record array fields accessed by index or by attribute are returned as a record array if the field has a structured type but as a plain ndarray otherwise. >>> recordarr = np.rec.array([('Hello', (1, 2)), ("World", (3, 4))], ... dtype=[('foo', 'S6'),('bar', [('A', int), ('B', int)])]) >>> type(recordarr.foo) <class 'numpy.ndarray'> >>> type(recordarr.bar) <class 'numpy.recarray'> Note that if a field has the same name as an ndarray attribute, the ndarray attribute takes precedence. Such fields will be inaccessible by attribute but will still be accessible by index. Recarray Helper Functions Collection of utilities to manipulate structured arrays. Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. numpy.lib.recfunctions.append_fields(base, names, data, dtypes=None, fill_value=- 1, usemask=True, asrecarray=False)[source] Add new fields to an existing array. The names of the fields are given with the names arguments, the corresponding values with the data arguments. If a single field is appended, names, data and dtypes do not have to be lists but just values. Parameters basearray Input array to extend. namesstring, sequence String or sequence of strings corresponding to the names of the new fields. dataarray or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypessequence of datatypes, optional Datatype or sequence of datatypes. If None, the datatypes are estimated from the data. fill_value{float}, optional Filling value used to pad missing data on the shorter arrays. usemask{False, True}, optional Whether to return a masked array or not. asrecarray{False, True}, optional Whether to return a recarray (MaskedRecords) or not. numpy.lib.recfunctions.apply_along_fields(func, arr)[source] Apply function ‘func’ as a reduction across fields of a structured array. This is similar to apply_along_axis, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from numpy.result_type applied to the field’s dtypes. Parameters funcfunction Function to apply on the “field” dimension. This function must support an axis argument, like np.mean, np.sum, etc. arrndarray Structured array for which to apply func. Returns outndarray Result of the recution operation Examples >>> from numpy.lib import recfunctions as rfn >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> rfn.apply_along_fields(np.mean, b) array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) array([ 3. , 5.5, 9. , 11. ]) numpy.lib.recfunctions.assign_fields_by_name(dst, src, zero_unassigned=True)[source] Assigns values from one structured array to another by field name. Normally in numpy >= 1.14, assignment of one structured array to another copies fields “by position”, meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name. This function instead copies “by field name”, such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13. Parameters dstndarray srcndarray The source and destination arrays during assignment. zero_unassignedbool, optional If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified. numpy.lib.recfunctions.drop_fields(base, drop_names, usemask=True, asrecarray=False)[source] Return a new array with fields in drop_names dropped. Nested fields are supported. Changed in version 1.18.0: drop_fields returns an array with 0 fields if all fields are dropped, rather than returning None as it did previously. Parameters basearray Input array drop_namesstring or sequence String or sequence of strings corresponding to the names of the fields to drop. usemask{False, True}, optional Whether to return a masked array or not. asrecarraystring or sequence, optional Whether to return a recarray or a mrecarray (asrecarray=True) or a plain ndarray or masked array with flexible dtype. The default is False. Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], ... dtype=[('a', np.int64), ('b', [('ba', np.double), ('bb', np.int64)])]) >>> rfn.drop_fields(a, 'a') array([((2., 3),), ((5., 6),)], dtype=[('b', [('ba', '<f8'), ('bb', '<i8')])]) >>> rfn.drop_fields(a, 'ba') array([(1, (3,)), (4, (6,))], dtype=[('a', '<i8'), ('b', [('bb', '<i8')])]) >>> rfn.drop_fields(a, ['ba', 'bb']) array([(1,), (4,)], dtype=[('a', '<i8')]) numpy.lib.recfunctions.find_duplicates(a, key=None, ignoremask=True, return_index=False)[source] Find the duplicates in a structured array along a given key Parameters aarray-like Input array key{string, None}, optional Name of the fields along which to check the duplicates. If None, the search is performed by records ignoremask{True, False}, optional Whether masked data should be discarded or considered as duplicates. return_index{False, True}, optional Whether to return the indices of the duplicated values. Examples >>> from numpy.lib import recfunctions as rfn >>> ndtype = [('a', int)] >>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3], ... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) >>> rfn.find_duplicates(a, ignoremask=True, return_index=True) (masked_array(data=[(1,), (1,), (2,), (2,)], mask=[(False,), (False,), (False,), (False,)], fill_value=(999999,), dtype=[('a', '<i8')]), array([0, 1, 3, 4])) numpy.lib.recfunctions.flatten_descr(ndtype)[source] Flatten a structured data-type description. Examples >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('a', '<i4'), ('b', [('ba', '<f8'), ('bb', '<i4')])]) >>> rfn.flatten_descr(ndtype) (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32'))) numpy.lib.recfunctions.get_fieldstructure(adtype, lastname=None, parents=None)[source] Returns a dictionary with fields indexing lists of their parent fields. This function is used to simplify access to fields nested in other fields. Parameters adtypenp.dtype Input datatype lastnameoptional Last processed field name (used internally during recursion). parentsdictionary Dictionary of parent fields (used interbally during recursion). Examples >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('A', int), ... ('B', [('BA', int), ... ('BB', [('BBA', int), ('BBB', int)])])]) >>> rfn.get_fieldstructure(ndtype) ... # XXX: possible regression, order of BBA and BBB is swapped {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']} numpy.lib.recfunctions.get_names(adtype)[source] Returns the field names of the input datatype as a tuple. Parameters adtypedtype Input datatype Examples >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names(np.empty((1,), dtype=int)) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)])) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names(adtype) ('a', ('b', ('ba', 'bb'))) numpy.lib.recfunctions.get_names_flat(adtype)[source] Returns the field names of the input datatype as a tuple. Nested structure are flattened beforehand. Parameters adtypedtype Input datatype Examples >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names_flat(np.empty((1,), dtype=int)) is None Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)])) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names_flat(adtype) ('a', 'b', 'ba', 'bb') numpy.lib.recfunctions.join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None, usemask=True, asrecarray=False)[source] Join arrays r1 and r2 on key key. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the key field cannot be found in the two input arrays. Neither r1 nor r2 should have any duplicates along key: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters key{string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2arrays Structured arrays. jointype{‘inner’, ‘outer’, ‘leftouter’}, optional If ‘inner’, returns the elements common to both r1 and r2. If ‘outer’, returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If ‘leftouter’, returns the common elements and the elements of r1 not in r2. r1postfixstring, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfixstring, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults{dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask{True, False}, optional Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray. asrecarray{False, True}, optional Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray. Notes The output is sorted along the key. A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates… numpy.lib.recfunctions.merge_arrays(seqarrays, fill_value=- 1, flatten=False, usemask=False, asrecarray=False)[source] Merge arrays field by field. Parameters seqarrayssequence of ndarrays Sequence of arrays fill_value{float}, optional Filling value used to pad missing data on the shorter arrays. flatten{False, True}, optional Whether to collapse nested fields. usemask{False, True}, optional Whether to return a masked array or not. asrecarray{False, True}, optional Whether to return a recarray (MaskedRecords) or not. Notes Without a mask, the missing value will be filled with something, depending on what its corresponding type: -1 for integers -1.0 for floating point numbers '-' for characters '-1' for strings True for boolean values XXX: I just obtained these values empirically Examples >>> from numpy.lib import recfunctions as rfn >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) array([( 1, 10.), ( 2, 20.), (-1, 30.)], dtype=[('f0', '<i8'), ('f1', '<f8')]) >>> rfn.merge_arrays((np.array([1, 2], dtype=np.int64), ... np.array([10., 20., 30.])), usemask=False) array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('f0', '<i8'), ('f1', '<f8')]) >>> rfn.merge_arrays((np.array([1, 2]).view([('a', np.int64)]), ... np.array([10., 20., 30.])), ... usemask=False, asrecarray=True) rec.array([( 1, 10.), ( 2, 20.), (-1, 30.)], dtype=[('a', '<i8'), ('f1', '<f8')]) numpy.lib.recfunctions.rec_append_fields(base, names, data, dtypes=None)[source] Add new fields to an existing array. The names of the fields are given with the names arguments, the corresponding values with the data arguments. If a single field is appended, names, data and dtypes do not have to be lists but just values. Parameters basearray Input array to extend. namesstring, sequence String or sequence of strings corresponding to the names of the new fields. dataarray or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypessequence of datatypes, optional Datatype or sequence of datatypes. If None, the datatypes are estimated from the data. Returns appended_arraynp.recarray See also append_fields numpy.lib.recfunctions.rec_drop_fields(base, drop_names)[source] Returns a new numpy.recarray with fields in drop_names dropped. numpy.lib.recfunctions.rec_join(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None)[source] Join arrays r1 and r2 on keys. Alternative to join_by, that always returns a np.recarray. See also join_by equivalent function numpy.lib.recfunctions.recursive_fill_fields(input, output)[source] Fills fields from output with fields from input, with support for nested structures. Parameters inputndarray Input array. outputndarray Output array. Notes output should be at least the same size as input Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', np.int64), ('B', np.float64)]) >>> b = np.zeros((3,), dtype=a.dtype) >>> rfn.recursive_fill_fields(a, b) array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', '<i8'), ('B', '<f8')]) numpy.lib.recfunctions.rename_fields(base, namemapper)[source] Rename the fields from a flexible-datatype ndarray or recarray. Nested fields are supported. Parameters basendarray Input array whose fields must be modified. namemapperdictionary Dictionary mapping old field names to their new version. Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], ... dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])]) >>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'}) array([(1, (2., [ 3., 30.])), (4, (5., [ 6., 60.]))], dtype=[('A', '<i8'), ('b', [('ba', '<f8'), ('BB', '<f8', (2,))])]) numpy.lib.recfunctions.repack_fields(a, align=False, recurse=False)[source] Re-pack the fields of a structured array or dtype in memory. The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap. This method removes any overlaps and reorders the fields in memory so they have increasing byte offsets, and adds or removes padding bytes depending on the align option, which behaves like the align option to np.dtype. If align=False, this method produces a “packed” memory layout in which each field starts at the byte the previous field ended, and any padding bytes are removed. If align=True, this methods produces an “aligned” memory layout in which each field’s offset is a multiple of its alignment, and the total itemsize is a multiple of the largest alignment, by adding padding bytes as needed. Parameters andarray or dtype array or dtype for which to repack the fields. alignboolean If true, use an “aligned” memory layout, otherwise use a “packed” layout. recurseboolean If True, also repack nested structures. Returns repackedndarray or dtype Copy of a with fields repacked, or a itself if no repacking was needed. Examples >>> from numpy.lib import recfunctions as rfn >>> def print_offsets(d): ... print("offsets:", [d.fields[name][1] for name in d.names]) ... print("itemsize:", d.itemsize) ... >>> dt = np.dtype('u1, <i8, <f8', align=True) >>> dt dtype({'names': ['f0', 'f1', 'f2'], 'formats': ['u1', '<i8', '<f8'], 'offsets': [0, 8, 16], 'itemsize': 24}, align=True) >>> print_offsets(dt) offsets: [0, 8, 16] itemsize: 24 >>> packed_dt = rfn.repack_fields(dt) >>> packed_dt dtype([('f0', 'u1'), ('f1', '<i8'), ('f2', '<f8')]) >>> print_offsets(packed_dt) offsets: [0, 1, 9] itemsize: 17 numpy.lib.recfunctions.require_fields(array, required_dtype)[source] Casts a structured array to a new dtype using assignment by field-name. This function assigns from the old to the new array by name, so the value of a field in the output array is the value of the field with the same name in the source array. This has the effect of creating a new ndarray containing only the fields “required” by the required_dtype. If a field name in the required_dtype does not exist in the input array, that field is created and set to 0 in the output array. Parameters andarray array to cast required_dtypedtype datatype for output array Returns outndarray array with the new dtype, with field values copied from the fields in the input array with the same name Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.ones(4, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')]) >>> rfn.require_fields(a, [('b', 'f4'), ('c', 'u1')]) array([(1., 1), (1., 1), (1., 1), (1., 1)], dtype=[('b', '<f4'), ('c', 'u1')]) >>> rfn.require_fields(a, [('b', 'f4'), ('newf', 'u1')]) array([(1., 0), (1., 0), (1., 0), (1., 0)], dtype=[('b', '<f4'), ('newf', 'u1')]) numpy.lib.recfunctions.stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, autoconvert=False)[source] Superposes arrays fields by fields Parameters arraysarray or sequence Sequence of input arrays. defaultsdictionary, optional Dictionary mapping field names to the corresponding default values. usemask{True, False}, optional Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray. asrecarray{False, True}, optional Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray. autoconvert{False, True}, optional Whether automatically cast the type of the field to the maximum. Examples >>> from numpy.lib import recfunctions as rfn >>> x = np.array([1, 2,]) >>> rfn.stack_arrays(x) is x True >>> z = np.array([('A', 1), ('B', 2)], dtype=[('A', '|S3'), ('B', float)]) >>> zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], ... dtype=[('A', '|S3'), ('B', np.double), ('C', np.double)]) >>> test = rfn.stack_arrays((z,zz)) >>> test masked_array(data=[(b'A', 1.0, --), (b'B', 2.0, --), (b'a', 10.0, 100.0), (b'b', 20.0, 200.0), (b'c', 30.0, 300.0)], mask=[(False, False, True), (False, False, True), (False, False, False), (False, False, False), (False, False, False)], fill_value=(b'N/A', 1.e+20, 1.e+20), dtype=[('A', 'S3'), ('B', '<f8'), ('C', '<f8')]) numpy.lib.recfunctions.structured_to_unstructured(arr, dtype=None, copy=False, casting='unsafe')[source] Converts an n-D structured array into an (n+1)-D unstructured array. The new array will have a new last dimension equal in size to the number of field-elements of the input array. If not supplied, the output datatype is determined from the numpy type promotion rules applied to all the field datatypes. Nested fields, as well as each element of any subarray fields, all count as a single field-elements. Parameters arrndarray Structured array or dtype to convert. Cannot contain object datatype. dtypedtype, optional The dtype of the output unstructured array. copybool, optional See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional See casting argument of ndarray.astype. Controls what kind of data casting may occur. Returns unstructuredndarray Unstructured array with one more dimension. Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.zeros(4, dtype=[('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) >>> a array([(0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.])], dtype=[('a', '<i4'), ('b', [('f0', '<f4'), ('f1', '<u2')]), ('c', '<f4', (2,))]) >>> rfn.structured_to_unstructured(a) array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> np.mean(rfn.structured_to_unstructured(b[['x', 'z']]), axis=-1) array([ 3. , 5.5, 9. , 11. ]) numpy.lib.recfunctions.unstructured_to_structured(arr, dtype=None, names=None, align=False, copy=False, casting='unsafe')[source] Converts an n-D unstructured array into an (n-1)-D structured array. The last dimension of the input array is converted into a structure, with number of field-elements equal to the size of the last dimension of the input array. By default all output fields have the input array’s dtype, but an output structured dtype with an equal number of fields-elements can be supplied instead. Nested fields, as well as each element of any subarray fields, all count towards the number of field-elements. Parameters arrndarray Unstructured array or dtype to convert. dtypedtype, optional The structured dtype of the output array nameslist of strings, optional If dtype is not supplied, this specifies the field names for the output dtype, in order. The field dtypes will be the same as the input array. alignboolean, optional Whether to create an aligned memory layout. copybool, optional See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional See casting argument of ndarray.astype. Controls what kind of data casting may occur. Returns structuredndarray Structured array with fewer dimensions. Examples >>> from numpy.lib import recfunctions as rfn >>> dt = np.dtype([('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) >>> a = np.arange(20).reshape((4,5)) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) >>> rfn.unstructured_to_structured(a, dt) array([( 0, ( 1., 2), [ 3., 4.]), ( 5, ( 6., 7), [ 8., 9.]), (10, (11., 12), [13., 14.]), (15, (16., 17), [18., 19.])], dtype=[('a', '<i4'), ('b', [('f0', '<f4'), ('f1', '<u2')]), ('c', '<f4', (2,))])
numpy.user.basics.rec
numpy.lib.recfunctions.apply_along_fields(func, arr)[source] Apply function ‘func’ as a reduction across fields of a structured array. This is similar to apply_along_axis, but treats the fields of a structured array as an extra axis. The fields are all first cast to a common type following the type-promotion rules from numpy.result_type applied to the field’s dtypes. Parameters funcfunction Function to apply on the “field” dimension. This function must support an axis argument, like np.mean, np.sum, etc. arrndarray Structured array for which to apply func. Returns outndarray Result of the recution operation Examples >>> from numpy.lib import recfunctions as rfn >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> rfn.apply_along_fields(np.mean, b) array([ 2.66666667, 5.33333333, 8.66666667, 11. ]) >>> rfn.apply_along_fields(np.mean, b[['x', 'z']]) array([ 3. , 5.5, 9. , 11. ])
numpy.user.basics.rec#numpy.lib.recfunctions.apply_along_fields
numpy.lib.recfunctions.assign_fields_by_name(dst, src, zero_unassigned=True)[source] Assigns values from one structured array to another by field name. Normally in numpy >= 1.14, assignment of one structured array to another copies fields “by position”, meaning that the first field from the src is copied to the first field of the dst, and so on, regardless of field name. This function instead copies “by field name”, such that fields in the dst are assigned from the identically named field in the src. This applies recursively for nested structures. This is how structure assignment worked in numpy >= 1.6 to <= 1.13. Parameters dstndarray srcndarray The source and destination arrays during assignment. zero_unassignedbool, optional If True, fields in the dst for which there was no matching field in the src are filled with the value 0 (zero). This was the behavior of numpy <= 1.13. If False, those fields are not modified.
numpy.user.basics.rec#numpy.lib.recfunctions.assign_fields_by_name
numpy.lib.recfunctions.drop_fields(base, drop_names, usemask=True, asrecarray=False)[source] Return a new array with fields in drop_names dropped. Nested fields are supported. Changed in version 1.18.0: drop_fields returns an array with 0 fields if all fields are dropped, rather than returning None as it did previously. Parameters basearray Input array drop_namesstring or sequence String or sequence of strings corresponding to the names of the fields to drop. usemask{False, True}, optional Whether to return a masked array or not. asrecarraystring or sequence, optional Whether to return a recarray or a mrecarray (asrecarray=True) or a plain ndarray or masked array with flexible dtype. The default is False. Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], ... dtype=[('a', np.int64), ('b', [('ba', np.double), ('bb', np.int64)])]) >>> rfn.drop_fields(a, 'a') array([((2., 3),), ((5., 6),)], dtype=[('b', [('ba', '<f8'), ('bb', '<i8')])]) >>> rfn.drop_fields(a, 'ba') array([(1, (3,)), (4, (6,))], dtype=[('a', '<i8'), ('b', [('bb', '<i8')])]) >>> rfn.drop_fields(a, ['ba', 'bb']) array([(1,), (4,)], dtype=[('a', '<i8')])
numpy.user.basics.rec#numpy.lib.recfunctions.drop_fields
numpy.lib.recfunctions.find_duplicates(a, key=None, ignoremask=True, return_index=False)[source] Find the duplicates in a structured array along a given key Parameters aarray-like Input array key{string, None}, optional Name of the fields along which to check the duplicates. If None, the search is performed by records ignoremask{True, False}, optional Whether masked data should be discarded or considered as duplicates. return_index{False, True}, optional Whether to return the indices of the duplicated values. Examples >>> from numpy.lib import recfunctions as rfn >>> ndtype = [('a', int)] >>> a = np.ma.array([1, 1, 1, 2, 2, 3, 3], ... mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype) >>> rfn.find_duplicates(a, ignoremask=True, return_index=True) (masked_array(data=[(1,), (1,), (2,), (2,)], mask=[(False,), (False,), (False,), (False,)], fill_value=(999999,), dtype=[('a', '<i8')]), array([0, 1, 3, 4]))
numpy.user.basics.rec#numpy.lib.recfunctions.find_duplicates
numpy.lib.recfunctions.flatten_descr(ndtype)[source] Flatten a structured data-type description. Examples >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('a', '<i4'), ('b', [('ba', '<f8'), ('bb', '<i4')])]) >>> rfn.flatten_descr(ndtype) (('a', dtype('int32')), ('ba', dtype('float64')), ('bb', dtype('int32')))
numpy.user.basics.rec#numpy.lib.recfunctions.flatten_descr
numpy.lib.recfunctions.get_fieldstructure(adtype, lastname=None, parents=None)[source] Returns a dictionary with fields indexing lists of their parent fields. This function is used to simplify access to fields nested in other fields. Parameters adtypenp.dtype Input datatype lastnameoptional Last processed field name (used internally during recursion). parentsdictionary Dictionary of parent fields (used interbally during recursion). Examples >>> from numpy.lib import recfunctions as rfn >>> ndtype = np.dtype([('A', int), ... ('B', [('BA', int), ... ('BB', [('BBA', int), ('BBB', int)])])]) >>> rfn.get_fieldstructure(ndtype) ... # XXX: possible regression, order of BBA and BBB is swapped {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'], 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']}
numpy.user.basics.rec#numpy.lib.recfunctions.get_fieldstructure
numpy.lib.recfunctions.get_names(adtype)[source] Returns the field names of the input datatype as a tuple. Parameters adtypedtype Input datatype Examples >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names(np.empty((1,), dtype=int)) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> rfn.get_names(np.empty((1,), dtype=[('A',int), ('B', float)])) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names(adtype) ('a', ('b', ('ba', 'bb')))
numpy.user.basics.rec#numpy.lib.recfunctions.get_names
numpy.lib.recfunctions.get_names_flat(adtype)[source] Returns the field names of the input datatype as a tuple. Nested structure are flattened beforehand. Parameters adtypedtype Input datatype Examples >>> from numpy.lib import recfunctions as rfn >>> rfn.get_names_flat(np.empty((1,), dtype=int)) is None Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> rfn.get_names_flat(np.empty((1,), dtype=[('A',int), ('B', float)])) Traceback (most recent call last): ... AttributeError: 'numpy.ndarray' object has no attribute 'names' >>> adtype = np.dtype([('a', int), ('b', [('ba', int), ('bb', int)])]) >>> rfn.get_names_flat(adtype) ('a', 'b', 'ba', 'bb')
numpy.user.basics.rec#numpy.lib.recfunctions.get_names_flat
numpy.lib.recfunctions.join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None, usemask=True, asrecarray=False)[source] Join arrays r1 and r2 on key key. The key should be either a string or a sequence of string corresponding to the fields used to join the array. An exception is raised if the key field cannot be found in the two input arrays. Neither r1 nor r2 should have any duplicates along key: the presence of duplicates will make the output quite unreliable. Note that duplicates are not looked for by the algorithm. Parameters key{string, sequence} A string or a sequence of strings corresponding to the fields used for comparison. r1, r2arrays Structured arrays. jointype{‘inner’, ‘outer’, ‘leftouter’}, optional If ‘inner’, returns the elements common to both r1 and r2. If ‘outer’, returns the common elements as well as the elements of r1 not in r2 and the elements of not in r2. If ‘leftouter’, returns the common elements and the elements of r1 not in r2. r1postfixstring, optional String appended to the names of the fields of r1 that are present in r2 but absent of the key. r2postfixstring, optional String appended to the names of the fields of r2 that are present in r1 but absent of the key. defaults{dictionary}, optional Dictionary mapping field names to the corresponding default values. usemask{True, False}, optional Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray. asrecarray{False, True}, optional Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray. Notes The output is sorted along the key. A temporary array is formed by dropping the fields not in the key for the two arrays and concatenating the result. This array is then sorted, and the common entries selected. The output is constructed by filling the fields with the selected entries. Matching is not preserved if there are some duplicates…
numpy.user.basics.rec#numpy.lib.recfunctions.join_by
numpy.lib.recfunctions.merge_arrays(seqarrays, fill_value=- 1, flatten=False, usemask=False, asrecarray=False)[source] Merge arrays field by field. Parameters seqarrayssequence of ndarrays Sequence of arrays fill_value{float}, optional Filling value used to pad missing data on the shorter arrays. flatten{False, True}, optional Whether to collapse nested fields. usemask{False, True}, optional Whether to return a masked array or not. asrecarray{False, True}, optional Whether to return a recarray (MaskedRecords) or not. Notes Without a mask, the missing value will be filled with something, depending on what its corresponding type: -1 for integers -1.0 for floating point numbers '-' for characters '-1' for strings True for boolean values XXX: I just obtained these values empirically Examples >>> from numpy.lib import recfunctions as rfn >>> rfn.merge_arrays((np.array([1, 2]), np.array([10., 20., 30.]))) array([( 1, 10.), ( 2, 20.), (-1, 30.)], dtype=[('f0', '<i8'), ('f1', '<f8')]) >>> rfn.merge_arrays((np.array([1, 2], dtype=np.int64), ... np.array([10., 20., 30.])), usemask=False) array([(1, 10.0), (2, 20.0), (-1, 30.0)], dtype=[('f0', '<i8'), ('f1', '<f8')]) >>> rfn.merge_arrays((np.array([1, 2]).view([('a', np.int64)]), ... np.array([10., 20., 30.])), ... usemask=False, asrecarray=True) rec.array([( 1, 10.), ( 2, 20.), (-1, 30.)], dtype=[('a', '<i8'), ('f1', '<f8')])
numpy.user.basics.rec#numpy.lib.recfunctions.merge_arrays
numpy.lib.recfunctions.rec_append_fields(base, names, data, dtypes=None)[source] Add new fields to an existing array. The names of the fields are given with the names arguments, the corresponding values with the data arguments. If a single field is appended, names, data and dtypes do not have to be lists but just values. Parameters basearray Input array to extend. namesstring, sequence String or sequence of strings corresponding to the names of the new fields. dataarray or sequence of arrays Array or sequence of arrays storing the fields to add to the base. dtypessequence of datatypes, optional Datatype or sequence of datatypes. If None, the datatypes are estimated from the data. Returns appended_arraynp.recarray See also append_fields
numpy.user.basics.rec#numpy.lib.recfunctions.rec_append_fields
numpy.lib.recfunctions.rec_drop_fields(base, drop_names)[source] Returns a new numpy.recarray with fields in drop_names dropped.
numpy.user.basics.rec#numpy.lib.recfunctions.rec_drop_fields
numpy.lib.recfunctions.rec_join(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', defaults=None)[source] Join arrays r1 and r2 on keys. Alternative to join_by, that always returns a np.recarray. See also join_by equivalent function
numpy.user.basics.rec#numpy.lib.recfunctions.rec_join
numpy.lib.recfunctions.recursive_fill_fields(input, output)[source] Fills fields from output with fields from input, with support for nested structures. Parameters inputndarray Input array. outputndarray Output array. Notes output should be at least the same size as input Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, 10.), (2, 20.)], dtype=[('A', np.int64), ('B', np.float64)]) >>> b = np.zeros((3,), dtype=a.dtype) >>> rfn.recursive_fill_fields(a, b) array([(1, 10.), (2, 20.), (0, 0.)], dtype=[('A', '<i8'), ('B', '<f8')])
numpy.user.basics.rec#numpy.lib.recfunctions.recursive_fill_fields
numpy.lib.recfunctions.rename_fields(base, namemapper)[source] Rename the fields from a flexible-datatype ndarray or recarray. Nested fields are supported. Parameters basendarray Input array whose fields must be modified. namemapperdictionary Dictionary mapping old field names to their new version. Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))], ... dtype=[('a', int),('b', [('ba', float), ('bb', (float, 2))])]) >>> rfn.rename_fields(a, {'a':'A', 'bb':'BB'}) array([(1, (2., [ 3., 30.])), (4, (5., [ 6., 60.]))], dtype=[('A', '<i8'), ('b', [('ba', '<f8'), ('BB', '<f8', (2,))])])
numpy.user.basics.rec#numpy.lib.recfunctions.rename_fields
numpy.lib.recfunctions.repack_fields(a, align=False, recurse=False)[source] Re-pack the fields of a structured array or dtype in memory. The memory layout of structured datatypes allows fields at arbitrary byte offsets. This means the fields can be separated by padding bytes, their offsets can be non-monotonically increasing, and they can overlap. This method removes any overlaps and reorders the fields in memory so they have increasing byte offsets, and adds or removes padding bytes depending on the align option, which behaves like the align option to np.dtype. If align=False, this method produces a “packed” memory layout in which each field starts at the byte the previous field ended, and any padding bytes are removed. If align=True, this methods produces an “aligned” memory layout in which each field’s offset is a multiple of its alignment, and the total itemsize is a multiple of the largest alignment, by adding padding bytes as needed. Parameters andarray or dtype array or dtype for which to repack the fields. alignboolean If true, use an “aligned” memory layout, otherwise use a “packed” layout. recurseboolean If True, also repack nested structures. Returns repackedndarray or dtype Copy of a with fields repacked, or a itself if no repacking was needed. Examples >>> from numpy.lib import recfunctions as rfn >>> def print_offsets(d): ... print("offsets:", [d.fields[name][1] for name in d.names]) ... print("itemsize:", d.itemsize) ... >>> dt = np.dtype('u1, <i8, <f8', align=True) >>> dt dtype({'names': ['f0', 'f1', 'f2'], 'formats': ['u1', '<i8', '<f8'], 'offsets': [0, 8, 16], 'itemsize': 24}, align=True) >>> print_offsets(dt) offsets: [0, 8, 16] itemsize: 24 >>> packed_dt = rfn.repack_fields(dt) >>> packed_dt dtype([('f0', 'u1'), ('f1', '<i8'), ('f2', '<f8')]) >>> print_offsets(packed_dt) offsets: [0, 1, 9] itemsize: 17
numpy.user.basics.rec#numpy.lib.recfunctions.repack_fields
numpy.lib.recfunctions.require_fields(array, required_dtype)[source] Casts a structured array to a new dtype using assignment by field-name. This function assigns from the old to the new array by name, so the value of a field in the output array is the value of the field with the same name in the source array. This has the effect of creating a new ndarray containing only the fields “required” by the required_dtype. If a field name in the required_dtype does not exist in the input array, that field is created and set to 0 in the output array. Parameters andarray array to cast required_dtypedtype datatype for output array Returns outndarray array with the new dtype, with field values copied from the fields in the input array with the same name Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.ones(4, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')]) >>> rfn.require_fields(a, [('b', 'f4'), ('c', 'u1')]) array([(1., 1), (1., 1), (1., 1), (1., 1)], dtype=[('b', '<f4'), ('c', 'u1')]) >>> rfn.require_fields(a, [('b', 'f4'), ('newf', 'u1')]) array([(1., 0), (1., 0), (1., 0), (1., 0)], dtype=[('b', '<f4'), ('newf', 'u1')])
numpy.user.basics.rec#numpy.lib.recfunctions.require_fields
numpy.lib.recfunctions.stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, autoconvert=False)[source] Superposes arrays fields by fields Parameters arraysarray or sequence Sequence of input arrays. defaultsdictionary, optional Dictionary mapping field names to the corresponding default values. usemask{True, False}, optional Whether to return a MaskedArray (or MaskedRecords is asrecarray==True) or a ndarray. asrecarray{False, True}, optional Whether to return a recarray (or MaskedRecords if usemask==True) or just a flexible-type ndarray. autoconvert{False, True}, optional Whether automatically cast the type of the field to the maximum. Examples >>> from numpy.lib import recfunctions as rfn >>> x = np.array([1, 2,]) >>> rfn.stack_arrays(x) is x True >>> z = np.array([('A', 1), ('B', 2)], dtype=[('A', '|S3'), ('B', float)]) >>> zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)], ... dtype=[('A', '|S3'), ('B', np.double), ('C', np.double)]) >>> test = rfn.stack_arrays((z,zz)) >>> test masked_array(data=[(b'A', 1.0, --), (b'B', 2.0, --), (b'a', 10.0, 100.0), (b'b', 20.0, 200.0), (b'c', 30.0, 300.0)], mask=[(False, False, True), (False, False, True), (False, False, False), (False, False, False), (False, False, False)], fill_value=(b'N/A', 1.e+20, 1.e+20), dtype=[('A', 'S3'), ('B', '<f8'), ('C', '<f8')])
numpy.user.basics.rec#numpy.lib.recfunctions.stack_arrays
numpy.lib.recfunctions.structured_to_unstructured(arr, dtype=None, copy=False, casting='unsafe')[source] Converts an n-D structured array into an (n+1)-D unstructured array. The new array will have a new last dimension equal in size to the number of field-elements of the input array. If not supplied, the output datatype is determined from the numpy type promotion rules applied to all the field datatypes. Nested fields, as well as each element of any subarray fields, all count as a single field-elements. Parameters arrndarray Structured array or dtype to convert. Cannot contain object datatype. dtypedtype, optional The dtype of the output unstructured array. copybool, optional See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional See casting argument of ndarray.astype. Controls what kind of data casting may occur. Returns unstructuredndarray Unstructured array with one more dimension. Examples >>> from numpy.lib import recfunctions as rfn >>> a = np.zeros(4, dtype=[('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) >>> a array([(0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.]), (0, (0., 0), [0., 0.])], dtype=[('a', '<i4'), ('b', [('f0', '<f4'), ('f1', '<u2')]), ('c', '<f4', (2,))]) >>> rfn.structured_to_unstructured(a) array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]]) >>> b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)], ... dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')]) >>> np.mean(rfn.structured_to_unstructured(b[['x', 'z']]), axis=-1) array([ 3. , 5.5, 9. , 11. ])
numpy.user.basics.rec#numpy.lib.recfunctions.structured_to_unstructured
numpy.lib.recfunctions.unstructured_to_structured(arr, dtype=None, names=None, align=False, copy=False, casting='unsafe')[source] Converts an n-D unstructured array into an (n-1)-D structured array. The last dimension of the input array is converted into a structure, with number of field-elements equal to the size of the last dimension of the input array. By default all output fields have the input array’s dtype, but an output structured dtype with an equal number of fields-elements can be supplied instead. Nested fields, as well as each element of any subarray fields, all count towards the number of field-elements. Parameters arrndarray Unstructured array or dtype to convert. dtypedtype, optional The structured dtype of the output array nameslist of strings, optional If dtype is not supplied, this specifies the field names for the output dtype, in order. The field dtypes will be the same as the input array. alignboolean, optional Whether to create an aligned memory layout. copybool, optional See copy argument to ndarray.astype. If true, always return a copy. If false, and dtype requirements are satisfied, a view is returned. casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional See casting argument of ndarray.astype. Controls what kind of data casting may occur. Returns structuredndarray Structured array with fewer dimensions. Examples >>> from numpy.lib import recfunctions as rfn >>> dt = np.dtype([('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)]) >>> a = np.arange(20).reshape((4,5)) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) >>> rfn.unstructured_to_structured(a, dt) array([( 0, ( 1., 2), [ 3., 4.]), ( 5, ( 6., 7), [ 8., 9.]), (10, (11., 12), [13., 14.]), (15, (16., 17), [18., 19.])], dtype=[('a', '<i4'), ('b', [('f0', '<f4'), ('f1', '<u2')]), ('c', '<f4', (2,))])
numpy.user.basics.rec#numpy.lib.recfunctions.unstructured_to_structured
numpy.lib.user_array.container class numpy.lib.user_array.container(data, dtype=None, copy=True)[source] Standard container-class for easy multiple-inheritance. Methods copy tostring byteswap astype
numpy.reference.generated.numpy.lib.user_array.container
numpy.linspace numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)[source] Return evenly spaced numbers over a specified interval. Returns num evenly spaced samples, calculated over the interval [start, stop]. The endpoint of the interval can optionally be excluded. Changed in version 1.16.0: Non-scalar start and stop are now supported. Changed in version 1.20.0: Values are rounded towards -inf instead of 0 when an integer dtype is specified. The old behavior can still be obtained with np.linspace(start, stop, num).astype(int) Parameters startarray_like The starting value of the sequence. stoparray_like The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False. numint, optional Number of samples to generate. Default is 50. Must be non-negative. endpointbool, optional If True, stop is the last sample. Otherwise, it is not included. Default is True. retstepbool, optional If True, return (samples, step), where step is the spacing between samples. dtypedtype, optional The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred dtype will never be an integer; float is chosen even if the arguments would produce an array of integers. New in version 1.9.0. axisint, optional The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end. New in version 1.16.0. Returns samplesndarray There are num equally spaced samples in the closed interval [start, stop] or the half-open interval [start, stop) (depending on whether endpoint is True or False). stepfloat, optional Only returned if retstep is True Size of spacing between samples. See also arange Similar to linspace, but uses a step size (instead of the number of samples). geomspace Similar to linspace, but with numbers spaced evenly on a log scale (a geometric progression). logspace Similar to geomspace, but with the end points specified as logarithms. Examples >>> np.linspace(2.0, 3.0, num=5) array([2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([2. , 2.25, 2.5 , 2.75, 3. ]), 0.25) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 8 >>> y = np.zeros(N) >>> x1 = np.linspace(0, 10, N, endpoint=True) >>> x2 = np.linspace(0, 10, N, endpoint=False) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show()
numpy.reference.generated.numpy.linspace
numpy.load numpy.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII')[source] Load arrays or pickled objects from .npy, .npz or pickled files. Warning Loading files that contain object arrays uses the pickle module, which is not secure against erroneous or maliciously constructed data. Consider passing allow_pickle=False to load data that is known not to contain object arrays for the safer handling of untrusted sources. Parameters filefile-like object, string, or pathlib.Path The file to read. File-like objects must support the seek() and read() methods. Pickled files require that the file-like object support the readline() method as well. mmap_mode{None, ‘r+’, ‘r’, ‘w+’, ‘c’}, optional If not None, then memory-map the file, using the given mode (see numpy.memmap for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory. allow_picklebool, optional Allow loading pickled object arrays stored in npy files. Reasons for disallowing pickles include security, as loading pickled data can execute arbitrary code. If pickles are disallowed, loading object arrays will fail. Default: False Changed in version 1.16.3: Made default False in response to CVE-2019-6446. fix_importsbool, optional Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. If fix_imports is True, pickle will try to map the old Python 2 names to the new names used in Python 3. encodingstr, optional What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files in Python 3, which includes npy/npz files containing object arrays. Values other than ‘latin1’, ‘ASCII’, and ‘bytes’ are not allowed, as they can corrupt numerical data. Default: ‘ASCII’ Returns resultarray, tuple, dict, etc. Data stored in the file. For .npz files, the returned instance of NpzFile class must be closed to avoid leaking file descriptors. Raises OSError If the input file does not exist or cannot be read. UnpicklingError If allow_pickle=True, but the file cannot be loaded as a pickle. ValueError The file contains an object array, but allow_pickle=False given. See also save, savez, savez_compressed, loadtxt memmap Create a memory-map to an array stored in a file on disk. lib.format.open_memmap Create or load a memory-mapped .npy file. Notes If the file contains pickle data, then whatever object is stored in the pickle is returned. If the file is a .npy file, then a single array is returned. If the file is a .npz file, then a dictionary-like object is returned, containing {filename: array} key-value pairs, one for each file in the archive. If the file is a .npz file, the returned value supports the context manager protocol in a similar fashion to the open function: with load('foo.npz') as data: a = data['a'] The underlying file descriptor is closed when exiting the ‘with’ block. Examples Store data to disk, and load it again: >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]])) >>> np.load('/tmp/123.npy') array([[1, 2, 3], [4, 5, 6]]) Store compressed data to disk, and load it again: >>> a=np.array([[1, 2, 3], [4, 5, 6]]) >>> b=np.array([1, 2]) >>> np.savez('/tmp/123.npz', a=a, b=b) >>> data = np.load('/tmp/123.npz') >>> data['a'] array([[1, 2, 3], [4, 5, 6]]) >>> data['b'] array([1, 2]) >>> data.close() Mem-map the stored array, and then access the second row directly from disk: >>> X = np.load('/tmp/123.npy', mmap_mode='r') >>> X[1, :] memmap([4, 5, 6])
numpy.reference.generated.numpy.load
numpy.loadtxt numpy.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, like=None)[source] Load data from a text file. Each row in the text file must have the same number of values. Parameters fnamefile, str, pathlib.Path, list of str, generator File, filename, list, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators must return bytes or strings. The strings in a list or produced by a generator are treated as lines. dtypedata-type, optional Data-type of the resulting array; default: float. If this is a structured data-type, the resulting array will be 1-dimensional, and each row will be interpreted as an element of the array. In this case, the number of columns used must match the number of fields in the data-type. commentsstr or sequence of str, optional The characters or list of characters used to indicate the start of a comment. None implies no comments. For backwards compatibility, byte strings will be decoded as ‘latin1’. The default is ‘#’. delimiterstr, optional The string used to separate values. For backwards compatibility, byte strings will be decoded as ‘latin1’. The default is whitespace. convertersdict, optional A dictionary mapping column number to a function that will parse the column string into the desired value. E.g., if column 0 is a date string: converters = {0: datestr2num}. Converters can also be used to provide a default value for missing data (but see also genfromtxt): converters = {3: lambda s: float(s.strip() or 0)}. Default: None. skiprowsint, optional Skip the first skiprows lines, including comments; default: 0. usecolsint or sequence, optional Which columns to read, with 0 being the first. For example, usecols = (1,4,5) will extract the 2nd, 5th and 6th columns. The default, None, results in all columns being read. Changed in version 1.11.0: When a single column has to be read it is possible to use an integer instead of a tuple. E.g usecols = 3 reads the fourth column the same way as usecols = (3,) would. unpackbool, optional If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(...). When used with a structured data-type, arrays are returned for each field. Default is False. ndminint, optional The returned array will have at least ndmin dimensions. Otherwise mono-dimensional axes will be squeezed. Legal values: 0 (default), 1 or 2. New in version 1.6.0. encodingstr, optional Encoding used to decode the inputfile. Does not apply to input streams. The special value ‘bytes’ enables backward compatibility workarounds that ensures you receive byte arrays as results if possible and passes ‘latin1’ encoded strings to converters. Override this value to receive unicode arrays and pass strings as input to converters. If set to None the system default is used. The default value is ‘bytes’. New in version 1.14.0. max_rowsint, optional Read max_rows lines of content after skiprows lines. The default is to read all the lines. New in version 1.16.0. 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 Data read from the text file. See also load, fromstring, fromregex genfromtxt Load data with missing values handled as specified. scipy.io.loadmat reads MATLAB data files Notes This function aims to be a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values. New in version 1.10.0. The strings produced by the Python float.hex method can be used as input for floats. Examples >>> from io import StringIO # StringIO behaves like a file object >>> c = StringIO("0 1\n2 3") >>> np.loadtxt(c) array([[0., 1.], [2., 3.]]) >>> d = StringIO("M 21 72\nF 35 58") >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'), ... 'formats': ('S1', 'i4', 'f4')}) array([(b'M', 21, 72.), (b'F', 35, 58.)], dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')]) >>> c = StringIO("1,0,2\n3,0,4") >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True) >>> x array([1., 3.]) >>> y array([2., 4.]) This example shows how converters can be used to convert a field with a trailing minus sign into a negative number. >>> s = StringIO('10.01 31.25-\n19.22 64.31\n17.57- 63.94') >>> def conv(fld): ... return -float(fld[:-1]) if fld.endswith(b'-') else float(fld) ... >>> np.loadtxt(s, converters={0: conv, 1: conv}) array([[ 10.01, -31.25], [ 19.22, 64.31], [-17.57, 63.94]])
numpy.reference.generated.numpy.loadtxt
numpy.log numpy.log(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'log'> Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e. Parameters xarray_like Input value. outndarray, None, or tuple of ndarray and None, optional A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs. wherearray_like, optional This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. **kwargs For other keyword-only arguments, see the ufunc docs. Returns yndarray The natural logarithm of x, element-wise. This is a scalar if x is a scalar. See also log10, log2, log1p, emath.log Notes Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References 1 M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 67. https://personal.math.ubc.ca/~cbm/aands/page_67.htm 2 Wikipedia, “Logarithm”. https://en.wikipedia.org/wiki/Logarithm Examples >>> np.log([1, np.e, np.e**2, 0]) array([ 0., 1., 2., -Inf])
numpy.reference.generated.numpy.log
numpy.log10 numpy.log10(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'log10'> Return the base 10 logarithm of the input array, element-wise. 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 logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar. See also emath.log10 Notes Logarithm is a multivalued function: for each x there is an infinite number of z such that 10**z = x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log10 always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log10 is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log10 handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References 1 M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 67. https://personal.math.ubc.ca/~cbm/aands/page_67.htm 2 Wikipedia, “Logarithm”. https://en.wikipedia.org/wiki/Logarithm Examples >>> np.log10([1e-15, -3.]) array([-15., nan])
numpy.reference.generated.numpy.log10
numpy.log1p numpy.log1p(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'log1p'> Return the natural logarithm of one plus the input array, element-wise. Calculates log(1 + x). 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 Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar. See also expm1 exp(x) - 1, the inverse of log1p. Notes For real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy. Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = 1 + x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log1p always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log1p is a complex analytical function that has a branch cut [-inf, -1] and is continuous from above on it. log1p handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. References 1 M. Abramowitz and I.A. Stegun, “Handbook of Mathematical Functions”, 10th printing, 1964, pp. 67. https://personal.math.ubc.ca/~cbm/aands/page_67.htm 2 Wikipedia, “Logarithm”. https://en.wikipedia.org/wiki/Logarithm Examples >>> np.log1p(1e-99) 1e-99 >>> np.log(1 + 1e-99) 0.0
numpy.reference.generated.numpy.log1p
numpy.log2 numpy.log2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'log2'> Base-2 logarithm of x. 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 Base-2 logarithm of x. This is a scalar if x is a scalar. See also log, log10, log1p, emath.log2 Notes New in version 1.3.0. Logarithm is a multivalued function: for each x there is an infinite number of z such that 2**z = x. The convention is to return the z whose imaginary part lies in [-pi, pi]. For real-valued input data types, log2 always returns real output. For each value that cannot be expressed as a real number or infinity, it yields nan and sets the invalid floating point error flag. For complex-valued input, log2 is a complex analytical function that has a branch cut [-inf, 0] and is continuous from above on it. log2 handles the floating-point negative zero as an infinitesimal negative number, conforming to the C99 standard. Examples >>> x = np.array([0, 1, 2, 2**4]) >>> np.log2(x) array([-Inf, 0., 1., 4.]) >>> xi = np.array([0+1.j, 1, 2+0.j, 4.j]) >>> np.log2(xi) array([ 0.+2.26618007j, 0.+0.j , 1.+0.j , 2.+2.26618007j])
numpy.reference.generated.numpy.log2
numpy.logaddexp numpy.logaddexp(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'logaddexp'> Logarithm of the sum of exponentiations of the inputs. Calculates log(exp(x1) + exp(x2)). This function is useful in statistics where the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the logarithm of the calculated probability is stored. This function allows adding probabilities stored in such a fashion. Parameters x1, x2array_like Input values. 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 resultndarray Logarithm of exp(x1) + exp(x2). This is a scalar if both x1 and x2 are scalars. See also logaddexp2 Logarithm of the sum of exponentiations of inputs in base 2. Notes New in version 1.3.0. Examples >>> prob1 = np.log(1e-50) >>> prob2 = np.log(2.5e-50) >>> prob12 = np.logaddexp(prob1, prob2) >>> prob12 -113.87649168120691 >>> np.exp(prob12) 3.5000000000000057e-50
numpy.reference.generated.numpy.logaddexp
numpy.logaddexp2 numpy.logaddexp2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'logaddexp2'> Logarithm of the sum of exponentiations of the inputs in base-2. Calculates log2(2**x1 + 2**x2). This function is useful in machine learning when the calculated probabilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the base-2 logarithm of the calculated probability can be used instead. This function allows adding probabilities stored in such a fashion. Parameters x1, x2array_like Input values. 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 resultndarray Base-2 logarithm of 2**x1 + 2**x2. This is a scalar if both x1 and x2 are scalars. See also logaddexp Logarithm of the sum of exponentiations of the inputs. Notes New in version 1.3.0. Examples >>> prob1 = np.log2(1e-50) >>> prob2 = np.log2(2.5e-50) >>> prob12 = np.logaddexp2(prob1, prob2) >>> prob1, prob2, prob12 (-166.09640474436813, -164.77447664948076, -164.28904982231052) >>> 2**prob12 3.4999999999999914e-50
numpy.reference.generated.numpy.logaddexp2
numpy.logical_and numpy.logical_and(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'logical_and'> Compute the truth value of x1 AND x2 element-wise. Parameters x1, x2array_like Input arrays. 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 or bool Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars. See also logical_or, logical_not, logical_xor bitwise_and Examples >>> np.logical_and(True, False) False >>> np.logical_and([True, False], [False, False]) array([False, False]) >>> x = np.arange(5) >>> np.logical_and(x>1, x<4) array([False, False, True, True, False]) The & operator can be used as a shorthand for np.logical_and on boolean ndarrays. >>> a = np.array([True, False]) >>> b = np.array([False, False]) >>> a & b array([False, False])
numpy.reference.generated.numpy.logical_and
numpy.logical_not numpy.logical_not(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'logical_not'> Compute the truth value of NOT x element-wise. Parameters xarray_like Logical NOT is applied to the elements of x. 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 ybool or ndarray of bool Boolean result with the same shape as x of the NOT operation on elements of x. This is a scalar if x is a scalar. See also logical_and, logical_or, logical_xor Examples >>> np.logical_not(3) False >>> np.logical_not([True, False, 0, 1]) array([False, True, True, False]) >>> x = np.arange(5) >>> np.logical_not(x<3) array([False, False, False, True, True])
numpy.reference.generated.numpy.logical_not
numpy.logical_or numpy.logical_or(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'logical_or'> Compute the truth value of x1 OR x2 element-wise. Parameters x1, x2array_like Logical OR is applied to the elements of x1 and x2. 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 or bool Boolean result of the logical OR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars. See also logical_and, logical_not, logical_xor bitwise_or Examples >>> np.logical_or(True, False) True >>> np.logical_or([True, False], [False, False]) array([ True, False]) >>> x = np.arange(5) >>> np.logical_or(x < 1, x > 3) array([ True, False, False, False, True]) The | operator can be used as a shorthand for np.logical_or on boolean ndarrays. >>> a = np.array([True, False]) >>> b = np.array([False, False]) >>> a | b array([ True, False])
numpy.reference.generated.numpy.logical_or
numpy.logical_xor numpy.logical_xor(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'logical_xor'> Compute the truth value of x1 XOR x2, element-wise. Parameters x1, x2array_like Logical XOR is applied to the elements of x1 and x2. 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 ybool or ndarray of bool Boolean result of the logical XOR operation applied to the elements of x1 and x2; the shape is determined by broadcasting. This is a scalar if both x1 and x2 are scalars. See also logical_and, logical_or, logical_not, bitwise_xor Examples >>> np.logical_xor(True, False) True >>> np.logical_xor([True, True, False, False], [True, False, True, False]) array([False, True, True, False]) >>> x = np.arange(5) >>> np.logical_xor(x < 1, x > 3) array([ True, False, False, False, True]) Simple example showing support of broadcasting >>> np.logical_xor(0, np.eye(2)) array([[ True, False], [False, True]])
numpy.reference.generated.numpy.logical_xor
numpy.logspace numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)[source] Return numbers spaced evenly on a log scale. In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below). Changed in version 1.16.0: Non-scalar start and stop are now supported. Parameters startarray_like base ** start is the starting value of the sequence. stoparray_like base ** stop is the final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned. numinteger, optional Number of samples to generate. Default is 50. endpointboolean, optional If true, stop is the last sample. Otherwise, it is not included. Default is True. basearray_like, optional The base of the log space. The step size between the elements in ln(samples) / ln(base) (or log_base(samples)) is uniform. Default is 10.0. dtypedtype The type of the output array. If dtype is not given, the data type is inferred from start and stop. The inferred type will never be an integer; float is chosen even if the arguments would produce an array of integers. axisint, optional The axis in the result to store the samples. Relevant only if start or stop are array-like. By default (0), the samples will be along a new axis inserted at the beginning. Use -1 to get an axis at the end. New in version 1.16.0. Returns samplesndarray num samples, equally spaced on a log scale. See also arange Similar to linspace, with the step size specified instead of the number of samples. Note that, when used with a float endpoint, the endpoint may or may not be included. linspace Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space. geomspace Similar to logspace, but with endpoints specified directly. Notes Logspace is equivalent to the code >>> y = np.linspace(start, stop, num=num, endpoint=endpoint) ... >>> power(base, y).astype(dtype) ... Examples >>> np.logspace(2.0, 3.0, num=4) array([ 100. , 215.443469 , 464.15888336, 1000. ]) >>> np.logspace(2.0, 3.0, num=4, endpoint=False) array([100. , 177.827941 , 316.22776602, 562.34132519]) >>> np.logspace(2.0, 3.0, num=4, base=2.0) array([4. , 5.0396842 , 6.34960421, 8. ]) Graphical illustration: >>> import matplotlib.pyplot as plt >>> N = 10 >>> x1 = np.logspace(0.1, 1, N, endpoint=True) >>> x2 = np.logspace(0.1, 1, N, endpoint=False) >>> y = np.zeros(N) >>> plt.plot(x1, y, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.plot(x2, y + 0.5, 'o') [<matplotlib.lines.Line2D object at 0x...>] >>> plt.ylim([-0.5, 1]) (-0.5, 1) >>> plt.show()
numpy.reference.generated.numpy.logspace
numpy.longcomplex[source] alias of numpy.clongdouble
numpy.reference.arrays.scalars#numpy.longcomplex
class numpy.longdouble[source] Extended-precision floating-point number type, compatible with C long double but not necessarily with IEEE 754 quadruple-precision. Character code 'g' Alias numpy.longfloat Alias on this platform (Linux x86_64) numpy.float128: 128-bit extended-precision floating-point number type.
numpy.reference.arrays.scalars#numpy.longdouble
numpy.longfloat[source] alias of numpy.longdouble
numpy.reference.arrays.scalars#numpy.longfloat