The basic use of Python's numpy __python

Source: Internet
Author: User
Tags scalar true true
I. Overview of NumPy

NumPy (numerical python) provides Python support for multidimensional array objects: Ndarray, with vector computing power, fast, and space-saving. NumPy supports a large number of dimension groups and matrix operations, and also provides a large number of mathematical libraries for array operations. Second, create Ndarray arrays

Ndarray:n dimension Array Object (matrix), all elements must be of the same type.
Ndarray Property: The Ndim property that represents the number of dimensions, the Shape property, the dimension size, the Dtype property, and the data type.

To create a Ndarray array function:

code example:

#-*-Coding:utf-8-*-

import numpy;

print ' uses the list to generate a one-dimensional array '
data = [1,2,3,4,5,6]
x = Numpy.array (data)
print x #打印数组
print X.dtype #打印数组元素的类型

print ' Use list to generate two-dimensional array '
data = [[1,2],[3,4],[5,6]]
x = Numpy.array (data)
print x #打印数组
Print X.ndim # Prints the dimension of the array print
X.shape #打印数组各个维度的长度. Shape is a tuple

print ' Create an array using Zero/ones/empty: Create '
x = Numpy.zeros (6) #创建一维长度为6的 based on shape, elements are 1-d array
print X
x = Numpy.zeros ((2,3)) #创建一维长度为2, two-dimensional 0 array with two-dimensional length 3,
print x
x = Numpy.ones ((2,3)) #创建一维长度为2, two-dimensional 1 array of two-dimensional length 3
print x
x = Numpy.empty ((3,3)) #创建一维长度为2, two-dimensional length 3, uninitialized two-dimensional array
print x

print ' uses arrange to generate continuous elements '
Print Numpy.arange (6) # [0,1,2,3,4,5,] open interval
print numpy.arange (0,6,2)  # [0, 2,4]
Iii. specifying the type of Ndarray array element

NumPy Data type:

code example:

print ' generates an array of the specified element types: Setting the Dtype property '
x = Numpy.array ([1,2.6,3],dtype = Numpy.int64)
print x # element type is Int64
print X.dtype
x = Numpy.array ([1,2,3],dtype = Numpy.float64)
print x # element type is float64
print x.dtype

print ' Use Astype to copy an array and convert the type '
x = Numpy.array ([1,2.6,3],dtype = numpy.float64)
y = X.astype (numpy.int32)
print y # [1 2 3]
print x # [1.   2.6  3.]
z = Y.astype (numpy.float64)
Print Z # [1.  2.  3.]

print ' converts a string element to a numeric element '
x = Numpy.array ([' 1 ', ' 2 ', ' 3 '],dtype = numpy.string_)
y = X.astype (numpy.int32)
Print x # [' 1 ' 2 ' 3 ']
print y # [1 2 3] If the conversion fails

, the exception print ' is thrown using the data type of the other array as the parameter '
x = Numpy.array ([1., 2.6,3.] , dtype = Numpy.float32);
y = Numpy.arange (3,dtype=numpy.int32);
Print Y # [0 1 2]
print Y.astype (x.dtype) # [0.  1.  2.]
vectorization calculation of four and Ndarray

Vector operations: Operations between array keys of the same size are applied to the element
Vector and scalar operations: Broadcast-to "broadcast" a scalar to individual elements

code example:

print ' Ndarray array with scalar/array operations '
x = Numpy.array ([1,2,3]) 
print X*2 # [2 4 6]
print X>2 # [false False  true]< C4/>y = Numpy.array ([3,4,5])
print X+y # [4 6 8]
print X>y # [false false]
basic indexes and slices of ndarray arrays

Index of one-dimensional array: similar to Python's list indexing function

Index of multidimensional array: ARR[R1:R2, C1:C2] arr[1,1] equivalent arr[1][1] [:] Representing data for a dimension

code example:

The basic index of print ' Ndarray '
x = Numpy.array ([[[[1,2],[3,4],[5,6]])
print x[0] # [1,2]
print x[0][1] # 2, Index
Print x[0,1] # of normal python arrays
x = Numpy.array ([[[1, 2], [3,4]], [[5, 6], [7,8]])
print  X[0] # [[1 2],[3 4]]
y = x[0].copy () # generate a replica
z = x[0] # does not generate a copy of
print y #  [[1 2],[3 4]]
print y[0,0] # 1
y[0,0] = 0 
z[0,0] =-1
print y # [[0 2],[3 4]]
print x[0] # [[-1 2],[3 4]]
print Z # [[-1 2] , [3 4]]

print ' Ndarray slice '
x = Numpy.array ([1,2,3,4,5])
print X[1:3] # [2,3] right open interval
print x[:3] # [1,2 , 3] left defaults to 0
print x[1:] # [2,3,4,5] Right defaults to element number
print X[0:4:2] # [1,3] subscript increments 2
x = Numpy.array ([[1,2],[3,4],[5, 6]]
print x[:2] # [[1 2],[3 4]]
print x[:2,:1] # [[1],[3]]
x[:2,:1] = 0 # Assign a scalar value to
print x # [[0,2],[0,4 ],[5,6]]
x[:2,:1] = [[8],[6]] # Assign a value to the array
print x # [[8,2],[6,4],[5,6]]
Boolean index and fancy index of Ndarray array

Boolean index: Use a Boolean array as an index. Arr[condition],condition is a Boolean array consisting of a condition/multiple conditions.

Example of a Boolean index code:

The Boolean index of print ' Ndarray '
x = Numpy.array ([3,2,3,1,3,0])
# The length of the Boolean array must be consistent with the axis length of the index
y = Numpy.array ([True,false, True,false,true,false]) 
print x[y] # [3,3,3] 
print X[y==false] # [2,1,0]
print x>=3 # [True False  Tru  True  false]
print x[~ (x>=3)] # [2,1,0]
print (x==2) | ( x==1) # [False to  true false  ]
print x[(x==2) | ( X==1)] # [2 1]
x[(x==2) | ( x==1)] = 0
print x # [3 0 3 0 3 0]

Fancy index: An integer array is used as an index.

Fancy Index code example:

print ' Ndarray flower index: Use integral array as index '
x = Numpy.array ([1,2,3,4,5,6])
print x[[0,1,2] # [1 2 3]
print x[[-1,-2 , -3]] # [6,5,4]
x = Numpy.array ([[[[[1,2],[3,4],[5,6]]]
print x[[0,1]] # [[1,2],[3,4]]
print x[[0,1],[0,1] ] # [1,4] printing x[0][0] and x[1][1] Print
x[[0,1]][:,[0,1] # Print 01 Rows of 01 columns [[[1,2],[3,4]]
# Use the Numpy.ix_ () function to enhance readability
Print X[numpy.ix_ ([0,1],[0,1])] #同上 printing 01 rows of 01 columns [[[1,2],[3,4]]
x[[0,1],[0,1]] = [0,0]
print x # [[0,2],[3,0],[ 5,6]]
Ndarray and axis commutation of the array of seven

The transpose/axis swap of an array returns only one view of the source data and does not modify the source data.

code example:

print ' Ndarray array transpose and Axis swap '
k = numpy.arange (9) #[0,1,.... 8]
m = K.reshape ((3,3)) # Changing the array's shape copy to generate 2-dimensional array of 3 for each dimension print K # [0 1 2 3 4 5 6 7 8
]
print m # [[0 1 2] [3 4 5] [6 7 8]]
# transpose (Matrix) array: T property: Mt[x][y] = m[y][x]
print m.t # [[0 3 6] [1 4 7] [2 5 8]]
# COMPUTE the inner product XTX print of a matrix
Numpy.dot (m,m.t) # Numpy.dot dot Multiply
# The Axis object of the high dimensional array
k = Numpy.arange (8). Reshape (2,2,2)
print k # [[[0 1],[2 3]],[[4 5] , [6 7]]]
print k[1][0][0]
# Axis transform transpose parameter: tuple
m = K.transpose ((1,0,2)) # m[y][x][z = k[x][y][z]< C14/>print m # [[0 1],[4 5]],[[2 3],[6 7]]
print m[0][1][0]
# Axis Exchange swapaxes (axes: axes), parameters: pair of axis number
m = K.swapax ES (0,1) # swaps the first axis and the second axis m[y][x][z] = k[x][y][z]
print M # [[[0 1],[4 5]],[[2 3],[6 7]]]
print m[0][1][0]
# makes  Array matrix transpose by axis switching
m = Numpy.arange (9). Reshape ((3,3))
print M # [[0 1 2] [3 4 5] [6 7 8]]
print m.swapaxes (1,0) # [[0 3 6] [1 4 7] [2 5 8]]
Viii. Ndarray General functions

A common function (UFUNC) is a function that performs element-level operations on data in Ndarray.

One dollar Ufunc:

Unary Ufunc code example:

print ' unary Ufunc sample '
x = Numpy.arange (6)
print x # [0 1 2 3 4 5]
print Numpy.square (x) # [0  1  4 9 16
x = Numpy.array ([1.5,1.6,1.7,1.8])
y,z = NUMPY.MODF (x)
print y # [0.5 0.6 0.7  0.8]
Print Z # [1.  1.  1.  1.]

Binary Ufunc:

Binary Ufunc code example:

print ' Two Ufunc sample '
x = Numpy.array ([[[[[1,4],[6,7]])
y = Numpy.array ([[[2,3],[5,8]])
print numpy.maximum (x , y) # [[2,4],[6,8]]
print numpy.minimum (x,y) # [[1,3],[5,7]]
Nine, numpy where function is used

Np.where (condition, x, y), the first argument is a Boolean array, and the second and third arguments can be either scalar or array.

code example:

Use of print ' where function '
cond = Numpy.array ([true,false,true,false])
x = Numpy.where (cond,-2,2)
print x # [-2  2-2  2]
cond = Numpy.array ([1,2,3,4])
x = Numpy.where (cond>2,-2,2)
print x # [2  2-2 -2]
  
   y1 = Numpy.array ([ -1,-2,-3,-4])
y2 = Numpy.array ([1,2,3,4])
x = Numpy.where (cond>2,y1,y2) # length must match
The print x # [1,2,-3,-4]

print ' where function is nested using '
y1 = Numpy.array ([ -1,-2,-3,-4,-5,-6])
y2 = Numpy.array ([ 1,2,3,4,5,6])
y3 = Numpy.zeros (6)
cond = Numpy.array ([1,2,3,4,5,6])
x = Numpy.where (Cond>5,y3, Numpy.where (cond>2,y1,y2))
print x # [1.  2.-3. -4. -5.  0.]

  
10, Ndarray commonly used statistical methods

The data of the entire array/axis can be computed statistically by these basic statistical methods.

code example:

The basic statistical method of print ' NumPy '
x = Numpy.array ([[[1,2],[3,3],[1,2]]) #同一维度上的数组长度须一致
print X.mean () # 2
print X.mean ( Axis=1) # for the elements of each row average
print X.mean (axis=0) # for the elements of each column average
print x.sum () #同理
print X.sum (Axis=1) # [3 6 3]
Print X.max () # 3
print X.max (Axis=1) # [2 3 2]
print x.cumsum () # [1  3 6 9  ]
print X.cum Prod () # [1  2  6 18 18 36]

Statistical method for Boolean arrays: sum: Counts the number of true in a dimension of an array/array any: Statistics whether one/more of the dimensions in an array/array is true all: statistics whether the array/array is true in a dimension

code example:

print ' statistical method for Boolean arrays '
x = Numpy.array ([[[True,false],[true,false]])
print x.sum () # 2
print x.sum (Axis=1) # [1,1]
print X.any (axis=0) # [True,false]
print X.all (axis=1) # [False,false]

Use sort to sort arrays/arrays in place (the array itself is modified).

code example:

In-place ordering of print '. Sort '
x = Numpy.array ([[[1,6,2],[6,1,3],[1,5,2]]]
x.sort (axis=1) 
print x # [[1 2 6] [1 3 6] [1 2 5]]
#非就地排序: Numpy.sort () can produce a copy of an array
11, Ndarray of the array and set operation

code example: (Method return type is one-dimensional array (1d))

print ' Ndarray and set operations '
x = Numpy.array ([[[[1,6,2],[6,1,3],[1,5,2]])
print numpy.unique (x) # [1,2,3,5,6]
y = Numpy.array ([1,6,5])
print numpy.in1d (x,y) # [True True to  false  true True  false  True False]
print numpy.setdiff1d (x,y) # [2 3]
print numpy.intersect1d (x,y) # [1 5 6]
12. Linear algebra in NumPy

Import Numpy.linalg module. Linear algebra (linear algebra)

Common NUMPY.LINALG Module functions:

code example:

print ' linear algebra '
import numpy.linalg as NLA
print ' matrix dot multiply '
x = Numpy.array ([[1,2],[3,4]])
y = Numpy.array ([[[1,3],[2,4]])
Print X.dot (y) # [[5 11][11]]
print Numpy.dot (x,y) # [[5 11][11]]
print ' matrix reverse '
x = Numpy.array ([[ 1,1],[1,2]]
y = NLA.INV (x) # matrix inversion (if the inverse of the matrix exists)
print X.dot (y) # unit matrix [1.  0.][0.  1.]]
print Nla.det (x) # Find the determinant
13. Random number generation in NumPy

Import Numpy.random module.

Common Numpy.random Module functions:

code example:

print ' numpy.random random number generation '
import numpy.random as NPR

x = Npr.randint (0,2,size=100000) #抛硬币
print (x>0). The result of the sum () # positive
print Npr.normal (size= (2,2)) #正态分布随机数数组 shape = (2,2)
14, Ndarray array Remodeling

code example:

print ' Ndarray array reshape '
x = Numpy.arange (0,6) #[0 1 2 3 4]
print x #[0 1 2 3 4]
print x.reshape ((2,3)) # [[0 1 2][ 3 4 5]]
print x #[0 1 2 3 4]
print x.reshape ((2,3)). Reshape ((3,2)) # [[0 1][2 3][4 5]]
y = Numpy.array ([[1,1 , 1],[1,1,1]]
x = X.reshape (y.shape)
print x # [[0 1 2][3 4 5]]
print X.flatten () # [0 1 2 3 4 5]
X.FL Atten () [0] =-1 # Flatten returns copy
print X # [0 1 2][3 4 5]]
print x.ravel () # [0 1 2 3 4 + 5]
x.ravel () [0] =- 1 # Ravel returns the view (reference) 
print x # [[-1 1 2][3 4 5]]
print ' Dimension size auto derivation '
arr = numpy.arange
print Arr.resh Ape ((5,-1)) # 15/5 = 3
15. Splitting and merging of Ndarray arrays

code example:

print ' array merging and splitting ' x = Numpy.array ([[[1, 2, 3], [4, 5, 6]]) y = Numpy.array ([[7, 8, 9], [A, X]]) print Numpy.concatenat  E ([x, y], Axis = 0) # vertical combination [[1 2 3][4 5 6][7 8 9][10]] Print numpy.concatenate ([x, y], Axis = 1) # horizontal combination [[1 2 3 7 8 9][4 5 6]] print ' vertical stack and horizontal stack ' Print numpy.vstack ((x, y)) # vertical stack: Relative to vertical combined print numpy.hs
Tack ((x, y)) # Horizontal stack: # Dstack by depth stack print numpy.split (x,2,axis=0) # by row [Array ([1, 2, 3]]), Array ([[4, 5, 6]])] Print Numpy.split (X,3,axis=1) # Split by column [Array ([[[1],[4]]), Array ([[[2],[5]]), Array ([[[[3],[6]]]] # Stacking auxiliary class import NumPy as NP a rr = Np.arange (6) arr1 = Arr.reshape ((3, 2)) arr2 = Np.random.randn (3, 2) print ' R_ used to stack ' print np.r_[arr1, arr2 by row ' [[        0.1.          ] [2.          3.] [4. 5.] [0.22621904 0.39719794] [ -1.2201912-0.23623549] [ -0.83229114-0.72678578]] ' print ' c_ is used to stack ' Print n by column '          P.C_[NP.R_[ARR1, arr2], arr] ' [0.        1.0.   ] [2.       3.1.          ] [4.        5.2.        ] [0.22621904 0.39719794 3.        ] [ -1.2201912-0.23623549 4.        ] [ -0.83229114-0.72678578 5.
 ] "' print ' slices directly into array ' Print np.c_[1:6, -10:-5] ' [[1-10] [2-9] [3-8] [4-7] [5-6]] '
16, the elements of the array repeat operation

code example:

The elements of the print ' array '
x = Numpy.array ([[[1,2],[3,4]]]
print x.repeat (2) # is repeated by element [1 1 2 2 3 3 4 4]
print x.repeat (2, axis=0) # Repeat by line [[1 2][1 2][3 4][3 4]]
print x.repeat (2,axis=1) # Repeat in columns [[1 1 2 2][3 3 4 4]]
x = Numpy.array ([1,2]) C6/>print Numpy.tile (x,2) # Tile Tiles: [1 2 1 2]
print numpy.tile (x, (2, 2))  # Specifies the number of times from the low dimension to the high dimension to replicate. 
# [[1 2 1 2][1 2 1 2]]
All code: Github
Related Article

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.