Common numpy usage

Source: Internet
Author: User
This article introduces common numpy usage and details numpy introduction

The existence of numpy gives python powerful matrix computing capabilities, which is no less powerful than matlab.
Official documentation (https://docs.scipy.org/doc/numpy-dev/user/quickstart.html)

Usage

The data type and ndarray type in numpy are different from array. array in the standard library.

Ndarray attributes

Ndarray. ndim
The number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.
Ndarray. shape
The dimensions of the array. this is a tuple of integers indicating the size of the array in each dimension. for a matrix with n rows and m columns, shape will be (n, m ). the length of the shape tuple is therefore the rank, or number of dimensions, ndim.
Ndarray. size
The total number of elements of the array. This is equal to the product of the elements of shape.
Ndarray. dtype
An object describing the type of the elements in the array. one can create or specify dtype's using standard Python types. additionally NumPy provides types of its own. numpy. int32, numpy. int16, and numpy. float64 are some examples.
Ndarray. itemsize
The size in bytes of each element of the array. for example, an array of elements of type float64 has itemsize 8 (= 64/8), while one of type complex32 has itemsize 4 (= 32/8 ). it is equivalent to ndarray. dtype. itemsize.
Ndarray. data
The buffer containing the actual elements of the array. Normally, we won't need to use this attribute because we will access the elements in an array using indexing facilities.

Create an ndarray
>>> import numpy as np>>> a = np.array([2,3,4])>>> aarray([2, 3, 4])>>> a.dtypedtype('int64')>>> b = np.array([1.2, 3.5, 5.1])>>> b.dtypedtype('float64')

Two-dimensional array

>>> b = np.array([(1.5,2,3), (4,5,6)])>>> barray([[ 1.5,  2. ,  3. ],       [ 4. ,  5. ,  6. ]])

Type specified during creation

>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )>>> carray([[ 1.+0.j,  2.+0.j],       [ 3.+0.j,  4.+0.j]])

Create some special matrices

>>> np.zeros( (3,4) )array([[ 0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.]])>>> np.ones( (2,3,4), dtype=np.int16 )                # dtype can also be specifiedarray([[[ 1, 1, 1, 1],        [ 1, 1, 1, 1],        [ 1, 1, 1, 1]],       [[ 1, 1, 1, 1],        [ 1, 1, 1, 1],        [ 1, 1, 1, 1]]], dtype=int16)>>> np.empty( (2,3) )                                 # uninitialized, output may varyarray([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],       [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])

Create some matrices with specific rules

>>> np.arange( 10, 30, 5 )array([10, 15, 20, 25])>>> np.arange( 0, 2, 0.3 )                 # it accepts float argumentsarray([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])>>> from numpy import pi>>> np.linspace( 0, 2, 9 )                 # 9 numbers from 0 to 2array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25,  1.5 ,  1.75,  2.  ])>>> x = np.linspace( 0, 2*pi, 100 )        # useful to evaluate function at lots of points>>> f = np.sin(x)
Some Basic operations

Addition, subtraction, multiplication, division, and trigonometric functions

>>> a = np.array( [20,30,40,50] )>>> b = np.arange( 4 )>>> barray([0, 1, 2, 3])>>> c = a-b>>> carray([20, 29, 38, 47])>>> b**2array([0, 1, 4, 9])>>> 10*np.sin(a)array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])>>> a<35array([ True, True, False, False], dtype=bool)

Matrix operations
Matlab has. *,./, and so on.
However, in numpy, if +,-, ×,/is used, the addition, subtraction, multiplication, and division between vertices are preferentially executed.
If two matrices (phalanx) can perform operations between elements, and the matrix operation can take precedence over operations between elements

>>> import numpy as np>>> A = np.arange(10,20)>>> B = np.arange(20,30)>>> A + Barray([30, 32, 34, 36, 38, 40, 42, 44, 46, 48])>>> A * Barray([200, 231, 264, 299, 336, 375, 416, 459, 504, 551])>>> A / Barray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])>>> B / Aarray([2, 1, 1, 1, 1, 1, 1, 1, 1, 1])

To perform a matrix operation, it is generally a matrix multiplication operation.

>>> A = np.array([1,1,1,1])>>> B = np.array([2,2,2,2])>>> A.reshape(2,2)array([[1, 1],       [1, 1]])>>> B.reshape(2,2)array([[2, 2],       [2, 2]])>>> A * Barray([2, 2, 2, 2])>>> np.dot(A,B)8>>> A.dot(B)8

Some common global functions

>>> B = np.arange(3)>>> Barray([0, 1, 2])>>> np.exp(B)array([ 1.        ,  2.71828183,  7.3890561 ])>>> np.sqrt(B)array([ 0.        ,  1.        ,  1.41421356])>>> C = np.array([2., -1., 4.])>>> np.add(B, C)array([ 2.,  0.,  6.])
Index partition traversal of a matrix
>>> a = np.arange(10)**3>>> aarray([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])>>> a[2]8>>> a[2:5]array([ 8, 27, 64])>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000>>> aarray([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])>>> a[ : :-1]                                 # reversed aarray([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])>>> for i in a:...     print(i**(1/3.))...nan1.0nan3.0nan5.06.07.08.09.0

Matrix traversal

>>> import numpy as np>>> b = np.arange(16).reshape(4, 4)>>> for row in b:...  print(row)... [0 1 2 3][4 5 6 7][ 8  9 10 11][12 13 14 15]>>> for node in b.flat:...  print(node)... 0123456789101112131415
Special matrix operations

Change matrix shape-reshape

>>> a = np.floor(10 * np.random.random((3,4)))>>> aarray([[ 6.,  5.,  1.,  5.],       [ 5.,  5.,  8.,  9.],       [ 5.,  5.,  9.,  7.]])>>> a.ravel()array([ 6.,  5.,  1.,  5.,  5.,  5.,  8.,  9.,  5.,  5.,  9.,  7.])>>> aarray([[ 6.,  5.,  1.,  5.],       [ 5.,  5.,  8.,  9.],       [ 5.,  5.,  9.,  7.]])

Difference between resize and reshape
Resize will change the original matrix, and reshape will not

>>> aarray([[ 6.,  5.,  1.,  5.],       [ 5.,  5.,  8.,  9.],       [ 5.,  5.,  9.,  7.]])>>> a.reshape(2,-1)array([[ 6.,  5.,  1.,  5.,  5.,  5.],       [ 8.,  9.,  5.,  5.,  9.,  7.]])>>> aarray([[ 6.,  5.,  1.,  5.],       [ 5.,  5.,  8.,  9.],       [ 5.,  5.,  9.,  7.]])>>> a.resize(2,6)>>> aarray([[ 6.,  5.,  1.,  5.,  5.,  5.],       [ 8.,  9.,  5.,  5.,  9.,  7.]])

Matrix merging

>>> a = np.floor(10*np.random.random((2,2)))>>> aarray([[ 8.,  8.],       [ 0.,  0.]])>>> b = np.floor(10*np.random.random((2,2)))>>> barray([[ 1.,  8.],       [ 0.,  4.]])>>> np.vstack((a,b))array([[ 8.,  8.],       [ 0.,  0.],       [ 1.,  8.],       [ 0.,  4.]])>>> np.hstack((a,b))array([[ 8.,  8.,  1.,  8.],       [ 0.,  0.,  0.,  4.]])

The above is a detailed description of common numpy usage. For more information, see other related articles in the first PHP community!

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.