Memorandum-Summary of basic methods of NumPy

Source: Internet
Author: User
Tags array sort square root


First, array method

Create an array: Arange () creates a one-dimensional array; Array () creates a one-dimensional or multidimensional array whose parameters are similar to an array of objects, such as lists, etc.

Create array: Np.zeros ((2,3)), or np.ones ((2,3)), parameter is a tuple representing the number of rows and columns, respectively

The corresponding elements are multiplied, a * b, and a new matrix is obtained

Mathematically defined matrix multiplication Np.dot (A, B). if a shape mismatch is an error, but if a, B is a one-dimensional array, the inner product of the vector is returned

Reading an array element: such as a[0],a[0,0]

Array morphing: such as B=a.reshape (2,3,4) will get an array of three-dimensional array that the original array becomes 2*3*4, or a.shape= (2,3,4) or a.resize (2,3,4) Directly changes the shape of the array a

Array combinations: Horizontal combination hstack ((a) or concatenate (A, B), Axis=1), vertical combination vstack ((a) or concatenate ((A, B), axis=0), depth combination dstack ((b))

Array segmentation (opposite to array combination): Hsplit,vsplit,dsplit,split (split vs. concatenate)

Change NP array to py list: A.tolist ()

Array sort (small to large): column arrangement Np.msort (a), row arrangement Np.sort (a), Np.argsort (a) return subscript after sorting

Sort by plural: np.sort_complex (a) Sort by the imaginary part after the first real part

Insert of array: np.searchsorted (A, A, b) inserts a into the original ordered array A, and returns the index value of the inserted element

Type conversions: such as a.astype (int), NP's data types are richer than py, and each type has a conversion method

Conditional lookup, returns the index value of an array element that satisfies a condition: np.where (conditional)

Conditional lookup, return subscript: np.argwhere (condition)

Conditional lookup, returning an array element that satisfies a condition: np.extract ([Conditional],a)

Find the corresponding element in a according to the element in B as an index: Np.take (A, b) one-dimensional

Index of the smallest largest element in the array: Np.argmin (a), Np.argmax (a)

Comparison of element sizes at corresponding positions in multiple arrays: Np.maximum (a,b,c,.....) Returns the maximum value at each index location, np.minimum (...) instead

Place elements in A to B:a.fill (b)

exponent of each array element: Np.exp (a)

Generates a vector of linear lines: for example, Np.linspace (1,6,10) yields a uniform distribution between 1 and 6, returning a total of 10 numbers

Remainder: Np.mod (a,n) equivalent to A%n,np.fmod (A,n) is still the remainder of the balance of the positive and negative by a decision

Calculated average: Np.mean (a)

Calculates the weighted average: Np.average (A, b), where a weight

Calculate the extreme difference of an array: Np.pth (a) =max (a)-min (a)

Calculate variance (population variance): Np.var (a)

Standard deviation: np.std (a)

Arithmetic square root, A is the type of floating-point number: Np.sqrt (a)

Logarithm: Np.log (a)

Trims the array, swapping the number less than x in the array to x, and the number greater than Y to Y:a.clip (x, y)

Product of all array elements: A.prod ()

Cumulative product of array elements: A.cumprod ()

The symbol for the array element: Np.sign (a), which returns the positive and negative signs of each element in the array, denoted by 1 and 1

Array element class: Np.piecewise (a,[condition],[return value]), segment given value, classify the element according to the judging condition, and return the set return value.

Determine if the two array is equal: Np.array_equal (A, B)

Determine if an array element is a real number: Np.isreal (a)

Remove the elements from the array in the 0: Np.trim_zeros (a)

Rounding of floating-point numbers, but not changing floating-point number types: Np.rint (a)

Second, array properties

1. Get the size of each dimension of the array: A.shape

2. Get the array dimension: A.ndim

3. Number of elements: a.size

4. Number of bytes in memory of array elements: A.itemsize

5. Array of bytes: a.nbytes==a.size*a.itemsize

6. Array element overrides: A.flat=1, the array elements in a are covered by 1

7. Array transpose: A. T

Can not seek inverse, covariance, trace, etc., does not apply to complex scientific calculations, the array may be converted into matrix.

Third, matrix method

Create matrix: Np.mat (' ... ') is created through a string format, Np.mat (a) is created from array arrays, or it can be created with the matrix or Bmat function

Create composite matrix: Np.bmat (' A B ', ' ab '), create composite matrix AB with A and B (string format)

To create a n*n-dimensional unit matrix: Np.eye (N)

Transpose of the matrix: A.T

Inverse matrix of matrices: A.I

Calculate covariance matrix: Np.cov (x), Np.cov

Calculating traces of matrices (diagonal elements and): A.trace ()

Correlation coefficient: Np.corrcoef (x, y)

Give the diagonal element: a.diagonal ()

Four, linear algebra

Estimating coefficients in a linear model: A=NP.LINALG.LSTSQ (x,b), with B=a*x

Finding the inverse matrix of matrices: NP.LINALG.INV (A)

Generalized inverse matrices: NP.LINALG.PINV (A)

To find the determinant of a matrix: Np.linalg.det (A)

A set of linear equations such as ax=b: Np.linalg.solve (A, B)

To find the eigenvalues of a matrix: Np.linalg.eigvals (A)

Finding eigenvalues and eigenvectors: Np.linalg.eig (A)

SVD decomposition: NP.LINALG.SVD (A)

Five, probability distribution

Random number of two distributions: Np.random.binomial (n,p,size= ...), where n,p,size is the number of tests per round, probability, number of rounds

Generate hypergeometric distribution random number: Np.random.hypergeometric (n1,n2,n,size= ...), where the meaning of the parameters is the total value of objects 1, the total number of objects 2, each sample, the number of tests

Random number generating n normal distribution: Np.random.normal (mean, standard deviation, N)

Random number generating N logarithmic normal distribution: Np.random.lognormal (mean,sigma,n)

Vi. polynomial

Polynomial fitting: poly= np.polyfit (x,a,n), fitting point set a obtains n-level polynomial, where x is the transverse length, and the coefficients of the polynomial are returned.

Polynomial derivation function: Np.polyder (poly), coefficient of return derivative function

Get the N-order function of polynomial: polynomial. Deriv (m = n)

Polynomial seeking root: np.roots (poly)

The value of a polynomial at a point: Np.polyval (Poly,x[n]), which returns the value of the poly polynomial on the horizontal point x[n]

Two polynomial do difference operation: Np.polysub (A, B)

Matpoltlib Simple Drawing method

Introduce a simple drawing package import Matplotlib.pyplot as PLT, and finally display the image with Plt.show ()

Basic Drawing methods: Plt.plot (x, y), Plt.xlabel (' x '), Plt.ylabel (' y '), Plt.title (' ... ')

Sub-graph: Plt.subplot (ABC), where ABC represents the number of rows, columns, and ordinal of a sub-graph, respectively

To create a top-level container for a drawing component: Fig = Plt.figure ()

Add a sub-diagram: Ax = fig.add_subplot (ABC)

Set the master locator on the horizontal axis: Ax.xaxis.set_major_locator (...)

Draw Square Diagram: Plt.hist (A, b), A is the left horizontal axis value of a rectangle, column height

Plot scatter plot: plt.scatter (x,y,c = ' ... ', s =.), c for color, s for size

Add grid line: Plt.grid (True)

Add comments: such as ax.annotate (' X ', Xy=xpoint, textcoords= ' offsetpoints ', xytext= ( -50, +), arrowprops=dict (arrowstyle= "))

Add legend: such as Plt.legend (loc= ' best ', fancybox=true)

logarithm of coordinates: horizontal PLT.SEMILOGX (), ordinate plt.semilogy (), Horizontal longitudinal plt.loglog ()

Memorandum-Summary of basic methods of NumPy

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.