Python Scientific computing-Numpy quick start

Source: Internet
Author: User
Python Scientific computing-Numpy quick start

What is Numpy?

Numpy is a Python Scientific computing library that provides matrix computing functions. it is generally used with Scipy and matplotlib. It can be used to store and process large matrices, which is much more efficient than the nested list structure of Python itself (this structure can also be used to represent matrices )).


NumPy (Numeric Python) provides many advanced numerical programming tools, such as matrix data types, vector processing, and precision computation libraries. This product is designed for strict digital processing. It is mostly used by many large financial companies, as well as core scientific computing organizations such as Lawrence Livermore. NASA uses it to process tasks originally used in C ++, Fortran, or Matlab.


Multi-dimensional array


The multi-dimensional array type is numpy. ndarray.


Use numpy. array method


Use the list or tuple variable as the parameter to generate a one-dimensional array:

>>> 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)))
 


Use the list or tuple variable as the element to generate a two-dimensional array:

>>> print(np.array([[1,2],[3,4]]))[[1 2] [3 4]]


Data type

For example, numpy. int32, numpy. int16, and numpy. float64:

>>> print np.array((1.2,2,3,4), dtype=np.int32)[1 2 3 4]

Use the numpy. arange method

>>> print(np.arange(15))[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]>>> print type(np.arange(15))
 
  >>> print np.arange(15).reshape(3,5)[[ 0  1  2  3  4] [ 5  6  7  8  9] [10 11 12 13 14]]>>> print type(np.arange(15).reshape(3,5))
  
 

Use the numpy. linspace method

For example, a number of 9 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

Use numpy. zeros, numpy. ones, numpy. eye

A specific matrix can be constructed.

>>> 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 3D 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.]]]

Obtain the attributes of an array.

>>> A = np. zeros (2, 3) >>> print (. ndim) # dimension of the array 3 >>> print (. shape) # size (2, 3, 2)> print (. size) # Number of elements in the array 12 >>> print (. dtype) # element type float64 >>> print (. itemsize) #8 bytes for each element

Array index, slice, and assignment

>>> A = np. array ([[2, 3, 4], [5, 6, 7]) >>> print () [[2 3 4] [5 6 7] >>> print (a [1, 2]) # index starts from 0 7 >>> print a [1,:] [5 6 7] >>> print (a [: 2]) [6] >>> a [1,:] =, 10] # direct assignment >>> print (a) [[2 3 4] [8 9 10]

Use the for Operation ELEMENT

>>> for x in np.linspace(1,3,3):...     print(x)...1.02.03.0

Basic Array Operations

First, construct arrays a and B:

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

Addition, subtraction, multiplication, and division of arrays

>>> print(a > 2)[[False 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)[[ 16.  0] [ 0  16.]]

Methods that come with array objects

>>>. Sum () # The number of elements in a is 4.0>. sum (axis = 0) # calculate the sum ([2 ., 2.]) >>> a. min () 1.0 >>>. max () 1.0 use 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) # matrix multiplication array ([2 ., 2.], [2 ., 2.])

Merge arrays

Use the vstack and hstack functions in numpy:

>>> A = np. ones (2, 2) >>> B = np. eye (2) >>> print (np. vstack (a, B) # v -- vertical [1. 1.] [1. 1.] [1. 0.] [0. 1.] >>> print (np. hstack (a, B) # h -- horizonal level as the name suggests [1. 1. 1. 0.] [1. 1. 0. 1.]

Check whether the two functions involve the shortest copy problem:

>>> c = np.hstack((a,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.]]

We can see that the change of elements in a and B does not affect c.


Deep copy array

The array object comes with the method of shortest copy and deep copy, but the method of deep copy is usually more:

>>> A = np. ones (2, 2) >>> B = a >>> print (B is a) True >>> c =. copy () # deep copy> 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's matrix calculation method

>>> import numpy.linalg as nplg1

Feature value and feature vector:

>>> print nplg.eig(a)(array([ 3.,  1.]), array([[ 0.        ,  0.70710678],       [ 1.        , -0.70710678]]))

Matrix object

The Matrix object in the numpy module is numpy. matrix, including the processing of matrix data, calculation of matrix, basic statistical functions, transpose, reversible, and so on, including the processing of complex numbers, all in the matrix object.


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


Returns a matrix in which data is an ndarray object or character form;


Dtype: data type;


Copy: bool type.

>>> A = np. matrix ('1 2 7; 3 4 8; 5 6 9') >>> a # The line feed of the matrix must be separated by semicolons, the internal data must be in the string format (''). Elements of the moment matrix ([1, 2, 7], # arrays must be separated by spaces. [3, 4, 8], [5, 6, 9]) >>> B = np. array ([[], []) >>> x = np. matrix (B) # The data in the matrix can be an array object. >>> Xmatrix ([[1, 5], [3, 2])

Attributes of a matrix object

Matrix. T transpose

: Returns the transpose matrix of the matrix.


Matrix. H hermitian (conjugate) transpose

: Return the matrix of the complex number matrix.


Matrix. I inverse

: Returns the inverse matrix of the matrix.


Matrix. A base array

: Array based on the returned matrix


Matrix object method


All ([axis, out]): determines whether all elements in the matrix are true along the given axis (non-0 is true)


Any ([axis, out]): determines whether the matrix element is true in the direction of the given axis. If an element is true, it is true.


Argmax ([axis, out]): returns the index of the maximum element (the location of the maximum element) in the direction of the given axis ).


Argmin ([axis, out]): returns the index of the smallest element in the direction of the given axis (location of the smallest element)


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


Astype (dtype [, order, casting, subok, copy]): copies the matrix data, and the data type is the specified data type.


Byteswap (inplace) Swap the bytes of the array elements


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


Clip (a_min, a_max [, out]): returns a new matrix. the element larger than the given element is a_max, and the smaller one is a_min.


Compress (condition [, axis, out]): returns a matrix that meets the conditions.


Conj (): returns the compound number of the complex number.


Conjugate (): returns the total number of elements in the complex number.


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


Cumprod ([axis, dtype, out]): returns the element accumulation matrix along the specified axis.


Cumsum ([axis, dtype, out]): returns the element accumulation and matrix along the specified axis.


Diagonal ([offset, axis1, axis2]): return the diagonal data in the matrix.


Dot (B [, out]): point multiplication of two matrices


Dump (file): stores the matrix as a specified file. you can use pickle. loads () or numpy. loads () such as a. dump ('d: \ a.txt ')


Dumps (): convert the data in the matrix to a string.


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


Flatten ([order]): converts a matrix into a one-dimensional form, but it is still a matrix object.


GetA (): Returns itself, but is returned as an ndarray.


GetA1 (): returns a flat (one-dimensional) array (ndarray)


GetH (): returns the transpose matrix of its own bounded complex numbers.


GetI (): returns the inverse matrix of itself.


GetT (): returns its transpose matrix.


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


Mean ([axis, dtype, out]): returns the mean value of a given axis.


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


Nonzero (): returns the index matrix of a non-zero element.


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


Ptp ([axis, out]): returns the maximum value in the specified axis minus the minimum value.


Put (indices, values [, mode]): replace the value at the position of the specified index (indices) in the matrix with the given value.


Ravel ([order]): returns an array, which is a one-dimensional array or a flat array.


Repeat (repeats [, axis]): elements in the repeat matrix, which can be repeated along the specified axis. repeats is the number of repeats.


Reshape (shape [, order]): changes the size of the matrix, for example, reshape ([2, 3]).


Resize (new_shape [, refcheck]): changes the size of the data.


Round ([decimals, out]): returns the matrix with the specified precision. the specified number of digits is rounded to five. if it is 1, a decimal number is reserved.


Searchsorted (v [, side, sorter]): searches for the index position of V in the matrix.


Sort ([axis, kind, order]): sorts the matrix or by axis.


Squeeze ([axis]): removes an axis with a length of 1.


Std ([axis, dtype, out, ddof]): returns the standard deviation of an 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): exchange data on two axes.


Take (indices [, axis, out, mode]): extract the data at the specified index location and return the data in a one-dimensional array or matrix (mainly depends on axis)


Tofile (fid [, sep, format]): Writes data in the matrix to a file in binary format.


Tolist (): converts a matrix into a list.


Tostring ([order]): converts a matrix into a python string.


Trace ([offset, axis1, axis2, dtype, out]): returns the sum of diagonal elements.


Transpose (* axes): returns the transpose matrix of the matrix without changing the original matrix.


Var ([axis, dtype, out, ddof]): returns the variance of matrix elements along the specified axis.


View ([dtype, type]): generate a matrix of the same data type but 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, False,  True]], dtype=bool)>>> a.all(axis=1)matrix([[False],[ True],[False]], dtype=bool)

Astype method

>>> a.astype(float)matrix([[ 12.,   3.,   5.],[ 32.,  23.,   9.],[ 10., -14.,  78.]])

Argsort method

>>> a=np.matrix('12 3 5; 32 23 9; 10 -14 78')>>> a.argsort()matrix([[1, 2, 0],[2, 1, 0],[1, 0, 2]])

Clip method

>>> amatrix([[ 12,   3,   5],[ 32,  23,   9],[ 10, -14,  78]])>>> a.clip(12,32)matrix([[12, 12, 12],[32, 23, 12],[12, 12, 32]])


Cumprod method

 >>> a.cumprod(axis=1)matrix([[    12,     36,    180],[    32,    736,   6624],[    10,   -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([10, 20, 30, 40])>>> condition = (a > 15) & (a < 35)>>> conditionarray([False, True, True, False], dtype=bool)>>> a.compress(condition)array([20, 30])>>> a[condition]                                      # same effectarray([20, 30])>>> compress(a >= 30, a)                              # this form aso existsarray([30, 40])>>> b = array([[10,20,30],[40,50,60]])>>> b.compress(b.ravel() >= 22)array([30, 40, 50, 60])>>> x = array([3,1,2])>>> y = array([50, 101])>>> b.compress(x >= 2, axis=1)                       # illustrates the use of the axis keywordarray([[10, 30],[40, 60]])>>> b.compress(y >= 100, axis=0)array([[40, 50, 60]])

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.