NumPy Common Functions (i)--constructing array functions and code examples

Source: Internet
Author: User
Tags iterable

NumPy is a basic module for the scientific calculation of Python. It is a Python library that provides a multidimensional array of objects, various derivative objects (such as shielded arrays and matrices), as well as various routines for array, math, logic, shape manipulation, sorting, selection, I/O and other fast operations, discrete Fourier transforms, basic linear algebra, basic statistical operations, stochastic simulations, and so on.

This article mainly lists the functions commonly used to construct arrays or become sub-modules

One, 0-1 arrays

empty(Shape [, Dtype,order]) returns a new array of the given shape and type without initializing the entry.

Empty_like (a [, Dtype,order,subok]) returns a new array of the same shape and type as the given array.

Eye (N [, M,k,dtype]) returns an array of 2-d with a diagonal line and 0.

identity (n [, Dtype]) returns an array of identities.

ones(Shape[,dtype,order]) returns a new array of a given shape and type, populated with one.

ones_like(a [, Dtype,order,subok]) returns an array of the same shape and type as the given array.

zeros(Shape[,dtype,order]) returns a new array of a given shape and type, padding zeros.

zeros_like(a [, Dtype,order,subok]) returns the zero group of the same shape and type as the given array.

Full (Shape,fill_value [, Dtype,order]) returns a new array of the given shape and type, populating the Fill_value.

full_like(A,fill_value [, Dtype,order,subok]) returns a complete array of the same shape and type as the given array.

code example:

1.empty (Shape [, Dtype,order])>>> Np.empty ([2, 2]) array ([[[ -9.74499359e+001, 6.69583040e-309], [2.13182611e-314, 3.06959433e-309]]) #rando M>>> Np.empty ([2, 2], Dtype=int) array ([[ -1073741821, -1067949133], [496041986, 19249760]]) #random
2.empty_like (A [, Dtype,order,subok])>>> a = ([array-like>>>], [4,5,6]) # A is np.empty_like (a) array ([[ -1073741821, -1073741821, 3], #r andom [0, 0, -1073741821]]) >>> a = Np.array ([[1., 2., 3.],[4.,5.,6.]) >>> Np.empty_like (a) array ([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], #random [4.38791518e-305 , -2.00000715e+000, 4.17269252e-309]])
3. Eye (N [, M,k,dtype])>>> Np.eye (2, Dtype=int) Array ([[1, 0], [0, 1]]) >>> Np.eye (3, k=1) array ([[0], 1., 0.], [0., 0., 1 .], [0., 0., 0.])
4.identity (n [, Dtype])>>> np.identity (3) Array ([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]
5.ones (Shape[,dtype,order])>>> Np.ones (5) array ([1., 1., 1., 1., 1.]) >>> Np.ones ((5,), Dtype=np.int) array ([1, 1, 1, 1, 1]) >>> Np.ones ((2, 1)) Array ([[1.], [1.]]) >>> s = (2,2) >>> Np.ones (s) Array ([[1., 1.], [1., 1.])
6.ones_like (A, Dtype=none, order= ' K ', subok=true)examples>>> x = Np.arange (6) >>> x = X.reshape ((2, 3)) >>> Xarray ([[0, 1, 2], [3, 4, 5]]) >& Gt;> np.ones_like (x) Array ([[1, 1, 1], [1, 1, 1]]) >>> y = Np.arange (3, Dtype=np.float) >>> Yarray ([ 0., 1., 2.]) >>> np.ones_like (y) array ([1., 1., 1.])
7.zeros (Shape, dtype=float, order= ' C ')>>> Np.zeros (5) array ([0., 0., 0., 0., 0.]) >>> Np.zeros ((5,), Dtype=np.int) array ([0, 0, 0, 0, 0]) >>> Np.zeros ((2, 1)) array ([[0.], [0.]]) >>> s = (2,2) >>> Np.zeros (s) array ([[0., 0.], [0., 0.]) >>> Np.zeros ((2,), dtype=[(' x ', ' I4 '), (' Y ', ' I4 ')]) # Custom Dtypearray ([(0, 0), (0, 0)], dtype=[(' x ', ' <i4 ' ), (' Y ', ' <i4 ')])
8.zeros_like (A, Dtype=none, order= ' K ', subok=true)examples>>> x = Np.arange (6) >>> x = X.reshape ((2, 3)) >>> Xarray ([[0, 1, 2], [3, 4, 5]]) >& Gt;> np.zeros_like (x) array ([[0, 0, 0], [0, 0, 0]]) >>> y = Np.arange (3, Dtype=np.float) >>> Yarray ([ 0., 1., 2.]) >>> np.zeros_like (y) array ([0., 0., 0.])
9.full (Shape, Fill_value, Dtype=none, order= ' C ')>>> Np.full ((2, 2), Np.inf) array ([[INF, INF], [INF, INF]]) >>> Np.full ((2, 2), Array ([[10, 10], [10, 10]])
10.full_like (A, Fill_value, Dtype=none, order= ' K ', subok=true)>>> x = Np.arange (6, Dtype=np.int) >>> np.full_like (x, 1) array ([1, 1, 1, 1, 1, 1]) >>> Np.full_li Ke (x, 0.1) array ([0, 0, 0, 0, 0, 0]) >>> np.full_like (x, 0.1, dtype=np.double) array ([0.1, 0.1, 0.1, 0.1, 0.1, 0.1] ) >>> np.full_like (x, Np.nan, dtype=np.double) array ([Nan, Nan, Nan, Nan, Nan, Nan]) >>> y = np.arange (6, dtype=np.double) >>> np.full_like (Y, 0.1) array ([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])

Ii. creating an array from existing data

Array (object[, Dtype, copy, order, Subok, Ndmin]) create an array

Asarray (a[, Dtype, order]) to convert the input to an array

Asanyarray (a[, Dtype, order]) converts the input to ndarray, but through the Ndarray subclass.

Asmatrix (data[, Dtype]) interprets the input as a matrix.

Copy (a[, order]) returns a copy of an array from an existing array

Frombuffer (buffer[, Dtype, Count, offset]) interprets the buffer as a one-dimensional array:

FromFile (file[, Dtype, Count, Sep]) constructs an array from data in a text or binary file.

fromfunction (function, shape, **kwargs) constructs an array by executing a function at each coordinate.

Fromiter (Iterable, dtype[, Count]) creates a new 1-dimensional array from an object that can be iterated.

fromstring (string[, Dtype, Count, Sep]) Initializes a new 1-d array from the original binary or text data in the string.

Loadtxt         (fname[, Dtype, comments, delimiter, ...]) Load data from a text file.

1. Array>>> Np.array ([1, 2, 3]) array ([1, 2, 3]) upcasting:>>> Np.array ([1, 2, 3.0]) array ([1., 2., 3.])  More than one dimension:>>> np.array ([[1, 2], [3, 4]]) array ([[1, 2], [3, 4]]) Minimum dimensions 2:>>> Np.array ([1, 2, 3], ndmin=2) array ([[[1, 2, 3]]) Type provided:>>> Np.array ([1, 2, 3], Dtype=complex) array ([1.+0.J , 2.+0.J, 3.+0.J]) Data-type consisting of more than one element:>>> x = Np.array ([x], (3,4)],dtype=[(' A ', ' < I4 '), (' B ', ' <i4 ')]) >>> x[' a ']array ([1, 3]) Creating an array from sub-classes:>>> Np.array (Np.mat ( ' 1 2; 3 4 ')) array ([[[1, 2], [3, 4]]) >>> Np.array (Np.mat (' 1 2; 3 4 '), subok=true) matrix ([[1, 2], [3, 4]])2. AsarrayConvert a list to an array:>>> a = [1, 2]>>> Np.asarray (a) array ([1, 2]) Existing arrays is not copied: >>> a = Np.array ([1, 2]) >>> Np.asarray (a) is Atrueif Dtype are set, array is copied only if Dtype does no T match:>>> a = Np.array ([1, 2], Dtype=np.float32) >>> Np.asarray (A, dtype=np.float32) is atrue>> > Np.asarray (A, Dtype=np.float64) is afalsecontrary to Asanyarray, Ndarray subclasses was not passed THROUGH:&GT;&GT;&G T Issubclass (Np.matrix, np.ndarray) true>>> a = Np.matrix ([[[1, 2]]) >>> Np.asarray (a) is afalse>> > Np.asanyarray (a) is Atrue3.asanyarrayConvert a list to an array:>>> a = [1, 2]>>> Np.asanyarray (a) array ([1, 2]) Instances of Ndarray Subclas SES is passed through as-is:>>> a = Np.matrix ([1, 2]) >>> Np.asanyarray (a) is Atrue4. Asmatrix>>> x = Np.array ([[1, 2], [3, 4]]) >>> m = Np.asmatrix (x) >>> x[0,0] = 5>>> Mmatrix ([[5, 2], [3, 4]])5. CopyCreate an array x, with a reference y and a copy z:>>> x = Np.array ([1, 2, 3]) >>> y = x>>> z = Np.copy (x) Note that if we modify X, y changes, but not z:>>> x[0] = 10>>> x[0] = = Y[0]true>>&gt ; X[0] = = Z[0]false6.frombuffer>>> s = ' Hello World ' >>> np.frombuffer (S, dtype= ' S1 ', count=5, offset=6) Array ([' W ', ' O ', ' r ', ' L ', ' d '], Dtype= ' | S1 ')7.fromfile>>> dt = Np.dtype ([' Time ', [(' min ', int), (' sec ', int)]),... (' temp ', float)]) >>> x = Np.zeros ((1,), DTYPE=DT) >>> x[' time ' [' min '] = 10; x[' temp ' = 98.25>>> Xarray ([((0), 98.25)],dtype=[(' Time ', [(' Min ', ' <i4 '), (' sec ', ' <i4 ')]), (' temp ') , ' <f8 ')]) Save The raw data to disk:>>> import os>>> fname = Os.tmpnam () >>> x.tofile (fname) R EAD the raw data from disk:>>> np.fromfile (fname, DTYPE=DT) Array ([((0), 98.25)],dtype=[(' Time ', [' min ', ' &L T;i4 '), (' sec ', ' <i4 ')]), (' temp ', ' <f8 ')]) the recommended to store and load data:>>> np.save (fname, X) >>> np.load (fname + ' NPY ') array ([((0), 98.25)],dtype=[(' Time ', [(' Min ', ' <i4 '), (' sec ', ' <i4 ')]), (' Temp ', ' <f8 ')])
8.fromfunction>>> np.fromfunction (lambda i, j:i = = J, (3, 3), Dtype=int) Array ([[True, False, False],[false, True, False],[fal SE, False, True]], Dtype=bool) >>> np.fromfunction (lambda I, J:i + J, (3, 3), Dtype=int) array ([[0, 1, 2],[1, 2, 3 ],[2, 3, 4]])9.fromiter>>> iterable = (x*x for x in range (5)) >>> Np.fromiter (iterable, Np.float) array ([0., 1., 4., 9., 16.])10.fromstring>>> np.fromstring (' \x01\x02 ', dtype=np.uint8) array ([1, 2], dtype=uint8) >>> np.fromstring (' 1 2 ', Dtype=int, sep= ") array ([1, 2]) >>> np.fromstring (' 1, 2 ', Dtype=int, sep= ', ') array ([1, 2]) >>> Np.fromstring (' \x01\x02\x03\x04\x05 ', dtype=np.uint8, count=3) Array ([1, 2, 3], dtype=uint8)Loadtxt.>>> from IO import Stringio # Stringio behaves like a file object>>> c = Stringio ("0 1\n2 3") >>&gt ; Np.loadtxt (c) Array ([[0., 1.],[2., 3.]]) >>> d = Stringio ("M 72\nf") >>> Np.loadtxt (d, dtype={' names ': (' gender ', ' age ', ' weight '),... ' Formats ': (' S1 ', ' I4 ', ' F4 ')}) array ([' M ', ' + ', ' 72.0 '), (' F ', ' + ', 58.0 ')],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) >>> Xarray ([1., 3.]) >>> Yarray ([2., 4.])

  

Iii. Generating sequences

Arange ([Start,] stop[, step,][, Dtype]) returns the value of the uniform interval within a given interval.

Linspace (Start, stop[, num, endpoint, ...]) Returns the number of evenly spaced intervals within the specified interval.

Logspace (Start, stop[, NUM, endpoint, base, ...]) Returns the number evenly spaced on the order of magnitude.

Geomspace (Start, stop[, num, endpoint, Dtype]) returns the average interval (geometric progression) of a number on a logarithmic scale.

Meshgrid (*xi, **kwargs) returns the coordinate matrix from the coordinate vector:

The Mgrid instance returns a dense multidimensional "Meshgrid".

Ogrid instance returns an open multidimensional "Meshgrid"

1.arange>>> Np.arange (3) array ([0, 1, 2]) >>> Np.arange (3.0) array ([0., 1., 2.]) >>> Np.arange (3,7) Array ([3, 4, 5, 6]) >>> Np.arange (3,7,2) Array ([3, 5])2. Linspace>>> 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.P Yplot as plt>>> N = 8>>> y = Np.zeros (n) >>> x1 = np.linspace (0, ten, N, Endpoint=true) &GT;&GT;&G T x2 = np.linspace (0, ten, N, Endpoint=false) >>> plt.plot (x1, y, ' o ') [<matplotlib.lines.line2d object at 0X...&G t;] >>> Plt.plot (x2, y + 0.5, ' o ') [<matplotlib.lines.line2d object at 0x...>]>>> plt.ylim ([-0.5, 1]) ( -0.5, 1) >>> plt.show ()3. Logspace>>> 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 ([, 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.pl OT (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 ()4.geomspace>>> np.geomspace (1, num=4) array ([1., 10., 100., 1000.]) >>> np.geomspace (1, num=3, Endpoint=false) array ([1., 10., 100.]) >>> np.geomspace (1, num=4, Endpoint=false) array ([1., 5.62341325, 31.6227766, 177.827941]) >>> n P.geomspace (1, num=9) array ([1., 2., 4., 8., 16., 32., 64., 128., 256.]) Note that the above is not produce exact integers:>>> np.geomspace (1, 2, num=9, Dtype=int) Array ([1, 4, 7, (127, (+), (+), (1, 4, 8, 16, 32, 64, 128, Np.around), (Np.geomspace (1, 2, num=9)). Astype (int) array ) negative, decreasing, and complex inputs are allowed:>>> geomspace (1, num=4) array ([1000., 100., 10., 1.]) >>> geomspace ( -1000,-1, num=4) array ([-1000., 100.,-10.,-1.]) >>> geomspace (1j, 1000j, num=4) # straight Linearray ([0. +1.J, 0. +10.J, 0. +100.J, 0.+1000.J]) >>> Geom Space ( -1+0j, 1+0j, num=5) # Circlearray ([ -1.00000000+0.J, -0.70710678+0.70710678j,0.00000000+1.J, 0.70710678+0.70710678J,1.00000000+0.J]) graphical illustration of endpoint parameter:>>> Import Matplotlib.pyplot as plt>>> N = 10>>> y = Np.zeros (N) >>> PLT.SEMILOGX (Np.geomspace (1, 1 (n, endpoint=true), Y + 1, ' o ') >>> PLT.SEMILOGX (Np.geomspace (1, +, N, endpoint=false), Y + 2, ' O ') >> > Plt.axis ([0.5, 0, 3]) >>> Plt.grid (True, color= ' 0.7 ', linestyle= '-', which= ' both ', axis= ' both ') >& Gt;> Plt.show ()5. Meshgrid>>> NX, NY = (3, 2) >>> x = Np.linspace (0, 1, nx) >>> y = np.linspace (0, 1, NY) >>> XV, Y v = Meshgrid (x, y) >>> xvarray ([[0., 0.5, 1.],[0., 0.5, 1.]]) >>> Yvarray ([[0., 0., 0.],[1., 1., 1.]]) >>> xv, YV = Meshgrid (x, Y, sparse=true) # make sparse output arrays>>> xvarray ([[0., 0.5, 1.]]) >>> Yvarray ([[0.],[1.]]) Meshgrid is very useful to evaluate functions on a grid.>>> x = Np.arange ( -5, 5, 0.1) >>> y = np.arange (- 5, 5, 0.1) >>> xx, yy = Meshgrid (x, y, sparse=true) >>> z = np.sin (xx**2 + yy**2)/(xx**2 + yy**2) >&gt ;> h = plt.contourf (x, Y, z)6.mgrid>>> Np.mgrid[0:5,0:5]array ([[[[[0], 0, 0, 0, 0],[1, 1, 1, 1, 1],[2, 2, 2, 2, 2],[3, 3, 3, 3, 3],[4, 4, 4, 4, 4]],[[0  , 1, 2, 3, 4],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4],[0, 1, 2, 3, 4]]) >>> Np.mgrid[-1:1:5j]array ([-1., -0.5, 0. , 0.5, 1. ])7.ogrid>>> from NumPy import ogrid>>> Ogrid[-1:1:5j]array ([-1.,-0.5, 0., 0.5, 1.]) >>> Ogrid[0:5,0:5][array ([[[0],[1],[2],[3],[4]]), Array ([[[0, 1, 2, 3, 4]])]

  

NumPy Common Functions (i)--constructing array functions and code examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.