Python Scientific Computing-numpy Quick Start

Source: Internet
Author: User

What is NumPy?

NumPy is a scientific computing library of Python that provides the functions of matrix operations, which are generally used in conjunction with SCIPY and Matplotlib. It can be used to store and manipulate large matrices, which is much more efficient than Python's own nested list (nested list structure) structure (which can also be used to represent matrices).


NumPy (Numeric Python) offers a number of advanced numerical programming tools such as matrix data types, vector processing, and sophisticated operations libraries. Designed for rigorous digital processing. Many of the major financial companies used, as well as the core scientific computing organizations such as: Lawrence Livermore,nasa use it to deal with some of the original use of C++,fortran or MATLAB and other tasks.


Multidimensional arrays


The type of the multidimensional array is: Numpy.ndarray


Using the Numpy.array method


Produces a one-dimensional array with a list or tuple variable as a parameter:

>>> Print (Np.array ([1,2,3,4]) [1 2 3 4]>>> print (Np.array ((1.2,2,3,4))) [1.2  2.   3.   4.] >>> Print Type (Np.array ((1.2,2,3,4)))
 
  


Produces a two-dimensional array of elements as a list or a tuple variable:

>>> Print (Np.array ([[[1,2],[3,4]])) [[1 2] [3 4]]


Specifying data types

such as Numpy.int32, Numpy.int16, and Numpy.float64, etc.:

>>> Print Np.array ((1.2,2,3,4), Dtype=np.int32) [1 2 3 4]

Using the Numpy.arange method

>>> print (Np.arange) [0  1  2  3  4  5  6  7  8  9 Ten 14]>> > Print type (np.arange)
 
  
   
  >>> print np.arange (All). Reshape (3,5) [[0  1  2  3  4] [5  6  7  8  9] [14]]>>> Print type (Np.arange () reshape (3,5))
  c21>
 
  

Using the Numpy.linspace method

For example, a 9 number is generated from 1 to 3:

>>> Print (Np.linspace (1,3,10)) [1.          1.22222222  1.44444444  1.66666667  1.88888889  2.11111111  2.33333333  2.55555556  2.77777778  3.        ]

Construct a specific matrix

Using Numpy.zeros,numpy.ones,numpy.eye

You can construct a specific matrix

>>> Print (Np.zeros ((3,4))) [[0.  0.  0.  0.] [0.  0.  0.  0.] [0.  0.  0.  0.]]>>> Print (Np.ones ((4,3))) [[1.  1.  1.] [1.  1.  1.] [1.  1.  1.] [1.  1.  1.]]>>> Print (Np.eye (4)) [[1.  0.  0.  0.] [0.  1.  0.  0.] [0.  0.  1.  0.] [0.  0.  0.  1.]

Create a three-dimensional array:

>>> Print (Np.ones (3,3,3)) [[[1].  1.  1.]  [1.  1.  1.]  [1.  1.  1.] [1.  1.  1.]  [1.  1.  1.]  [1.  1.  1.]] [[1].  1.  1.]  [1.  1.  1.]  [1.  1.  1.]

Get the properties of an array

>>> a = Np.zeros ((2,3,2)) >>> print (A.ndim)   #数组的维数3 >>> Print (a.shape)  #数组每一维的大小 (2, 3, 2) >>> print (a.size)   #数组的元素数12 >>> Print (a.dtype)  #元素类型float64 >>> Print ( a.itemsize)  #每个元素所占的字节数8

Array index, slice, assignment

>>>a = Np.array ([[[2,3,4],[5,6,7]]) >>> print (a) [[2 3 4] [5 6 7]]>>> print (a[1,2]) #index从0开始7 & gt;>> Print a[1,:][5 6 7]>>> print (A[1,1:2]) [6]>>> a[1,:] = [8,9,10] #直接赋值 >>> Print (a) [ [2  3  4] [8  9 10]]

Using the For Action element

>>> for X in Np.linspace (1,3,3): ...     Print (x) ... 1.02.03.0

Basic array Operations

First construct the array A, B:

>>> a = Np.ones ((2,2)) >>> B = Np.eye (2) >>> print (a) [[1].  1.] [1.  1.]]>>> print (b) [[1.  0.] [0.  1.]

Subtraction of arrays

>>> print (a > 2) [[FALSE] [false] [false]]>>> print (A+B) [[2].  1.] [1.  2.]]>>> print (A-B) [[0.  1.] [1.  0.]]>>> print (b*2) [[2.  0.] [0.  2.]]>>> print ((a*2) * (b*2)) [[4.  0.] [0.  4.]]>>> print (b/(a*2)) [[0.5  0.] [0.   0.5]]>>> print ((b*2) **4) [[  +] 0] [0  16.]

Using the Array object's own method

>>> a.sum () #a的元素个数4 .0>>> a.sum (axis=0)   #计算每一列 (a matrix-like column in a two-dimensional array) and an array ([2.,  2.]) >>> a.min () 1.0>>> A.max () 1.0 Use the method under NumPy >>> Np.sin (a) array ([[0.84147098,  0.84147098],       [0.84147098,  0.84147098]]) >>> Np.max (a) 1.0>>> Np.floor (a) array ([[1.,  1.],       [1.,  1.]) >>> Np.exp (a) array ([[2.71828183,  2.71828183],       [2.71828183,  2.71828183]]) >>> Np.dot (A,a)   # #矩阵乘法array ([[2.,  2.],       [2.,  2.])

Merging arrays

Use the Vstack and Hstack functions under NumPy:

>>> a = Np.ones ((2,2)) >>> B = Np.eye (2) >>> print (Np.vstack ((b))) #顾名思义 v--vertical  Vertical [ [1.  1.] [1.  1.] [1.  0.] [0.  1.] >>> Print (Np.hstack (b)) #顾名思义 h--horizonal level [[1].  1.  1.  0.] [1.  1.  0.  1.]

See if these two functions involve a shallow copy of the problem:

>>> C = Np.hstack ((b)) >>> print c[[1.  1.  1.  0.] [1.  1.  0.  1.]]>>> a[1,1] = 5>>> b[1,1] = 5>>> print c[[1.  1.  1.  0.] [1.  1.  0.  1.]

As you can see, the changes in the elements in A and b do not affect C.


Deep Copy Array

The array object comes with a shallow copy and a deep copy method, but it is generally more deep-copy:

>>> a = Np.ones ((2,2)) >>> B = a>>> print (b is a) true>>> C = a.copy ()  #深拷贝 >>& Gt C is Afalse

Basic matrix Operations

Transpose:

>>> a = Np.array ([[1,0],[2,3]]) >>> print (a) [[1 0] [2 3]]>>> print (A.transpose ()) [[1 2] [0 3]]

Numpy.linalg Methods for matrix operations

>>> Import Numpy.linalg as Nplg1

Eigenvalues, eigenvectors:

>>> print Nplg.eig (a) (Array ([3.,  1.]), array ([[0.        ,  0.70710678],       [1.        , 0.70710678]]) )

Matrix Object

The matrix objects in the NumPy module are Numpy.matrix, including the processing of matrix data, calculation of matrices, and basic statistical functions, transpose, reversibility, etc., including the processing of complex numbers, in the Matrix object.


Class Numpy.matrix (data,dtype,copy):


Returns a matrix where data is a Ndarray object or a character form;


Dtype: the type of data;


Copy: is of type bool.

>>> a = Np.matrix (' 1 2 7; 3 4 8; 5 6 9 ') >>> a             #矩阵的换行必须是用分号 (;) separated, internal data must be in the form of a string ("), Moment Matrix ([[1, 2, 7] ,       #阵的元素之间必须以空格隔开. [3, 4, 8],[5, 6, 9]]) >>> B=np.array ([[[1,5],[3,2]]) >>> X=np.matrix (b)   #矩阵中的data可以为数组对象. >>> Xmatrix ([[1, 5],[3, 2]])

Properties of the Matrix object

Matrix. T Transpose

: Returns the Matrix's transpose matrix


Matrix. H Hermitian (conjugate) transpose

: Returns the conjugate element matrix of a complex matrix


Matrix. I Inverse

: Returns the inverse matrix of a matrix


Matrix. A Base Array

: Returns the array based on the matrix


Methods for matrix objects


All ([axis, out]): Determines whether all elements of the matrix are true along a given axis (not 0 is true)


Any ([axis, out]): Determines whether the matrix element is true along the direction of the given axis, as long as one element is true.


Argmax ([axis, out]): Returns the index of the largest element (the position of the largest element) along the direction of the given axis.


Argmin ([axis, out]): Returns the index of the smallest element (the position of the smallest element) along the direction of the given axis


Argsort ([axis, kind, order]): Returns the sorted index matrix


Astype (dtype[, order, casting, Subok, copy]): Copy the matrix data and the data type to the specified data type


Byteswap (inplace) Swap The bytes of the array elements


Choose (choices[, out, mode]): Gets a new data matrix based on the given index (index from choices given)


Clip (A_min, a_max[, out]): Returns a new matrix with elements larger than the given element as A_max, small for a_min


Compress (condition[, axis, out]): Returns the matrix that satisfies the condition


CONJ (): Returns the conjugate complex number of a complex number


Conjugate (): Returns the conjugate complex element of all complex numbers


Copy ([order]): Copy a matrix and assign to another object, B=a.copy ()


Cumprod ([axis, Dtype, out]): Returns the cumulative matrix of elements along a specified axis


Cumsum ([axis, Dtype, out]): Returns the element accumulation and matrix along the specified axis


Diagonal ([Offset, axis1, Axis2]): Returns the diagonal data in the matrix


Dot (b[, out]): Two dot multiplication of matrices


Dump (file): Stores the matrix as a specified file, either through Pickle.loads () or numpy.loads () such as: A.dump (' D:\a.txt ')


Dumps (): Dumps the data of the matrix into a string.


Fill (value): Fills all elements in the matrix with the specified value


Flatten ([order]): Transforms a matrix into a one-dimensional form, but still a matrix object


Geta (): Returns itself, but returns as Ndarray


GetA1 (): Returns a flat (one-dimensional) array (Ndarray)


Geth (): Returns the conjugate complex transpose matrix of itself


Geti (): Returns the inverse of the matrix itself


Gett (): Returns the transpose matrix of itself


Max ([axis, out]): Returns the maximum value of the specified axis


Mean ([axis, Dtype, out]): Returns the mean value along the given axis direction


Min ([axis, out]): Returns the minimum value of the specified axis


Nonzero (): Returns the index matrix of a non-0 element


Prod ([axis, Dtype, out]): Returns the product of the matrix element on the specified axis square.


PTP ([axis, out]): Returns the maximum value minus the minimum value for the specified axis direction.


Put (indices, values[, mode]): Replaces the value of the given index (indices) position of the matrix with the given value


Ravel ([order]): Returns an array that is a one-dimensional array or a flat array


Repeat (repeats[, axis]): Repeats elements in the matrix, repeats the matrix element in the specified axis direction, and repeats the number of repetitions


Reshape (shape[, order]): Change the size of the matrix, such as: reshape ([2,3])


Resize (new_shape[, Refcheck]): Change the size of the data


Round ([decimals, out]): Returns the matrix after the specified precision, with the specified number of digits rounded, or 1 if one decimal is reserved


Searchsorted (v[, side, Sorter]): Search for the index position of V in the matrix


Sort ([axis, kind, order]): Sort the Matrix or sort by the direction of the axis


Squeeze ([axis]): Remove axis of length 1


STD ([axis, Dtype, out, Ddof]): Returns the standard deviation of the element along the direction of the specified axis.


SUM ([axis, Dtype, out]): Returns the sum of its elements along the direction of the specified axis


Swapaxes (Axis1, AXIS2): Swaps data in two axis directions.


Take (indices[, axis, out, mode]): Extracts the data at the specified index location and returns it as a one-dimensional array or matrix (mainly depending on axis)


ToFile (fid[, Sep, format]): Writes data from a matrix to a file in binary


ToList (): Convert Matrix to List form


ToString ([order]): Converts the matrix to a python string.


Trace ([Offset, axis1, Axis2, Dtype, out]): Returns the sum of the diagonal elements


Transpose (*axes): Returns the Matrix's transpose matrix without changing the original matrix


var ([axis, Dtype, out, Ddof]): Returns the variance of the matrix element along the specified axis direction


View ([Dtype, type]): Generates the same data, but the type is a matrix of the specified new type.


Example

>>> a = Np.asmatrix (' 0 2 7; 3 4 8; 5 0 9 ') >>> A.all () false>>> a.all (axis=0) matrix ([[False, Fals E,  True]], Dtype=bool) >>> a.all (Axis=1) matrix ([[false],[True],[false]], Dtype=bool)

Astype method

>>> A.astype (float) matrix ([[3.,   5.],[, 9.],[, -14.,  78.]])

Argsort method

>>> A=np.matrix (' 3 5; 9; 10-14 ") >>> A.argsort () matrix ([[1, 2, 0],[2, 1, 0],[1, 0, 2]])

Clip method

>>> Amatrix ([3, 5],[, Max,   9],[, -14, +  ]]) >>> a.clip (12,32) matrix ( [[12, 12, 12],[32, 23, 12],[12, 12, 32]]


Cumprod method

>>> A.cumprod (Axis=1) matrix ([[[]     180],[,    736,   6624],[   , -140,-10920]])

Cumsum method

>>> a.cumsum (Axis=1) matrix ([[12, 15, 20],[32, 55, 64],[10,-4, 74]])


ToList method

>>> b.tolist () [[12, 3, 5], [32, 23, 9], [10,-14, 78]]

ToFile method

>>> b.tofile (' D:\\b.txt ')

Compress () method

>>> from numpy Import *

>>> A = Array ([ten, +, +]) >>> condition = (A > +) & (A <) >>> Conditionarray ( [False, True, true, False], Dtype=bool) >>> a.compress (condition) array ([+]) >>> A[condition]                                      # same Effectarray ([+]) >>> compress (a >=, a)                              # this form aso Existsarray ([+]) >>> ; b = Array ([[[10,20,30],[40,50,60]]) >>> b.compress (B.ravel () >=) array ([X, Max, Max]) >>> × = Arra Y ([3,1,2]) >>> y = array ([101]) >>> b.compress (x >= 2, Axis=1) # illustrates the use of the                       Axi s Keywordarray ([[[60], 30],[40, X]]) >>> b.compress (y >=, axis=0) Array ([[[40, 50,]])
  • 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.