Basic use of Python's numpy

Source: Internet
Author: User
Tags scalar

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 advanced large number of dimension and matrix operations, and also provides a large number of mathematical libraries for array operations.

Ii. creating an array of Ndarray

ndarray:n-dimensional array objects (matrices), all elements must be of the same type.
Ndarray Property: The Ndim property, which represents the number of dimensions; the Shape property, which represents the size of each dimension; The Dtype property that represents the data type.

To create an Ndarray array function:

code example:

#-*-coding:utf-8-*-import numpy;print ' use list to generate one-dimensional array ' data = [ 1,2,3,4,5,6]x = Numpy.array (data) print x #打印数组print x.dtype #打印数组元素的类型print ' use list to generate a two-dimensional array ' data = [[1,2],[3,4],[5,6]]x = num Py.array (data) print x #打印数组print x.ndim #打印数组的维度print x.shape #打印数组各个维度的长度. Shape is a tuple print ' Create an array using Zero/ones/empty: Create ' x = Numpy.zeros (6) #创建一维长度为6的 from shape, elements are 1-dimensional arrays print xx = Numpy.zeros ((2,3) ) #创建一维长度为2 a two-dimensional 0 array with a two-dimensional length of 3 print xx = Numpy.ones ((2,3)) #创建一维长度为2, a two-dimensional 1 array with a two-dimensional length of 3, print xx = Numpy.empty ((3,3)) #创建一维长度为2, Two-dimensional length 3, uninitialized two-dimensional array print xprint ' using 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]  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
Iii. specifying the type of the Ndarray array element

NumPy Data type:

code example:

print ' generates an array of the specified element type: Set Dtype property ' x = Numpy.array ([1,2.6,3],dtype = Numpy.int64) Print x # element type Int64print X.dtypex = Numpy.array ([1,2,3],dtype = Numpy.float64) Print x # element type = Float64print x . dtypeprint ' Copy array with Astype and convert 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 ']p Rint y # [1 2 3] If the conversion failure throws an exception, print ' uses the data type of the other array as parameter ' x = Numpy.array ([1., 2.6,3.],dtype = numpy.float32); y = Numpy.arange (3  , Dtype=numpy.int32);p rint y # [0 1 2]print y.astype (x.dtype) # [0. 1.2.]  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
Vectorization Calculation of Ndarray

Vector operations: An operation between an array key of the same size applied to an element
Vector and scalar operations: "Broadcast"-scalar "broadcast" to individual elements

code example:

print ‘ndarray数组与标量/数组的运算‘x = numpy.array([1,2,3]) print x*2 # [2 4 6]print x>2 # [False False  True]y = numpy.array([3,4,5])print x+y # [4 6 8]print x>y # [False False False]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
V. Basic indexes and slices of the Ndarray array

Index of one-dimensional array: Similar to Python's list index function

Index of multidimensional arrays:

    • ARR[R1:R2, C1:C2]
    • arr[1,1] equivalent arr[1][1]
    • [:] represents data for a dimension

code example:

print ' Ndarray ' basic index ' x = Numpy.array ([[1,2],[3,4],[5,6]]) Print X[0] # [1,2]print x[0][1] # 2, index of normal python array print x[0,1] # Index of the x[0][1],ndarray array x = Numpy.array ([[[1, 2], [3,4]], [[5 , 6], [7,8]]) print x[0] # [[1 2],[3 4]]y = x[0].copy () # generate a copy z = x[0] # does not generate a copy print y # [[1 2],[3 4]]print y[0,0] # 1 y[0,0] = 0 z[0,0] = -1print y # [[0 2],[3 4]]print x[0] # [[-1 2],[3 4]]print z # [[-1 2],[3 4]]print ' ndarray slice ' x = nump  Y.array ([1,2,3,4,5]) print X[1:3] # [2,3] right open interval print x[:3] # [0print] The left default is:] # [x[1] The right default is the number of elements print 2,3,4,5] # [1,3] subscript increment 2x = 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 # with scalar Value print x # [[0,2],[0,4],[5,6]]x[:2,:1] = [[8],[6]] # Assign a value in an array print x # [[8,2],[6,4],[5,6]]  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
Vi. Boolean indexes and fancy indexes for ndarray arrays

Boolean index: Uses a Boolean array as the index. Arr[condition],condition is a Boolean array that consists of one condition/multiple conditions.

Example of a Boolean index code:

print ‘ndarray的布尔型索引‘x = numpy.array([3,2,3,1,3,0])# 布尔型数组的长度必须跟被索引的轴长度一致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  True False  True  False]print x[~(x>=3)] # [2,1,0]print (x==2)|(x==1) # [False  True False  True False False]print x[(x==2)|(x==1)] # [2 1]x[(x==2)|(x==1)] = 0print x # [3 0 3 0 3 0]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

Fancy index: Use an integer array as the index.

Fancy Index code example:

print ‘ndarray的花式索引:使用整型数组作为索引‘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] 打印x[0][0]和x[1][1]print x[[0,1]][:,[0,1]] # 打印01行的01列 [[1,2],[3,4]]# 使用numpy.ix_()函数增强可读性print x[numpy.ix_([0,1],[0,1])] #同上 打印01行的01列 [[1,2],[3,4]]x[[0,1],[0,1]] = [0,0]print x # [[0,2],[3,0],[5,6]]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
The transpose of the Ndarray array and the axis swap

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

code example:

print ' Ndarray ' the transpose and axes of the array ' k = Numpy.arange (9) #[0,1,.... 8]m = K.reshape ((3,3)) # Change the shape copy of the array to generate 2-dimensional, 3-dimensional array 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 of the matrix Xtxprint Numpy.dot (m,m.t) # Numpy.dot dot Multiply # high dimension Axis object of the Group 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: A tuple of axis numbers m = K.transpose ((1,0,2)) # M[y][x][z] = k[x][y][z]print m # [[[0 1],[4 5]],[[2 3],[6 7]]]print m[0][1][0]# axis swap swapaxes (a Xes: Axis), parameter: Pair of axes number M = k.swapaxes (0,1) # switch first and second axes m[y][x][z] = k[x][y][z]print m # [[[0 1],[4 5]],[[2 3],[6 7]]]print m[0] [1]  [0]# uses an axis interchange for array matrix transpose 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]]  
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
Viii. General functions of Ndarray

A general function (UFUNC) is a function that performs an element-level operation on data in Ndarray.

One dollar Ufunc:

One-dollar Ufunc code example:

print ‘一元ufunc示例‘x = numpy.arange(6)print x # [0 1 2 3 4 5]print numpy.square(x) # [ 0  1  4  9 16 25]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.]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

Dual Ufunc:

Binary Ufunc code example:

print ‘二元ufunc示例‘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]]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
Nine, the WHERE function of NumPy uses

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

code example:

print ‘where函数的使用‘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) # 长度须匹配print x # [1,2,-3,-4]print ‘where函数的嵌套使用‘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.]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
X. Statistical methods commonly used in Ndarray

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

code example:

print ‘numpy的基本统计方法‘x = numpy.array([[1,2],[3,3],[1,2]]) #同一维度上的数组长度须一致print x.mean() # 2print x.mean(axis=1) # 对每一行的元素求平均print x.mean(axis=0) # 对每一列的元素求平均print x.sum() #同理 12print x.sum(axis=1) # [3 6 3]print x.max() # 3print x.max(axis=1) # [2 3 2]print x.cumsum() # [ 1  3  6  9 10 12]print x.cumprod() # [ 1  2  6 18 18 36]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

Statistical methods for Boolean arrays:

    • Sum: Counts the number of true in a dimension of an array/array
    • Any: Statistics array/Array if there is one/more true in a dimension
    • All: counts whether the array/array is true in one dimension

code example:

print ‘用于布尔数组的统计方法‘x = numpy.array([[True,False],[True,False]])print x.sum() # 2print x.sum(axis=1) # [1,1]print x.any(axis=0) # [True,False]print x.all(axis=1) # [False,False]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

Use sort to sort the array/array in-place with a dimension (the arrays themselves are modified).

code example:

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()可产生数组的副本
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
The de-weight of the Ndarray array and the set operation

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

print ‘ndarray的唯一化和集合运算‘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 False  True  True False  True  True False]print numpy.setdiff1d(x,y) # [2 3]print numpy.intersect1d(x,y) # [1 5 6]
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
12. Linear Algebra in NumPy

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

Common NUMPY.LINALG Module functions:

code example:

print ‘线性代数‘import numpy.linalg as nlaprint ‘矩阵点乘‘x = numpy.array([[1,2],[3,4]])y = numpy.array([[1,3],[2,4]])print x.dot(y) # [[ 5 11][11 25]]print numpy.dot(x,y) # # [[ 5 11][11 25]]print ‘矩阵求逆‘x = numpy.array([[1,1],[1,2]])y = nla.inv(x) # 矩阵求逆(若矩阵的逆存在)print x.dot(y) # 单位矩阵 [[ 1.  0.][ 0.  1.]]print nla.det(x) # 求行列式
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
13. Generation of random numbers in NumPy

Import Numpy.random module.

Common Numpy.random Module functions:

code example:

print ‘numpy.random随机数生成‘import numpy.random as nprx = npr.randint(0,2,size=100000) #抛硬币print (x>0).sum() # 正面的结果print npr.normal(size=(2,2)) #正态分布随机数数组 shape = (2,2)
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
14. Ndarray Array Remodeling

code example:

print ‘ndarray数组重塑‘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.flatten()[0] = -1 # flatten返回的是拷贝print x # [[0 1 2][3 4 5]]print x.ravel() # [0 1 2 3 4 5]x.ravel()[0] = -1 # ravel返回的是视图(引用) print x # [[-1 1 2][3 4 5]]print "维度大小自动推导"arr = numpy.arange(15)print arr.reshape((5, -1)) # 15 / 5 = 3
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
The splitting and merging of the array of XV and Ndarray

code example:

The merge and split of print ' arrays ' x = Numpy.array ([[1, 2, 3], [4, 5, 6]]) y = Numpy.array ([[7, 8, 9], [Ten, One,]]) print numpy.concatenate ([  x, y], Axis = 0) # vertical combination [[1 2 3][4 5 6][7 8 9][10 one 12]]print numpy.concatenate ([x, y], Axis = 1) # horizontal combination [[1 2 3 7 8 9][4 5 6 12]]print ' vertical stack with horizontal stack ' Print numpy.vstack ((x, y)) # vertical stacking: With respect to the vertical combination of print numpy.hstack ((x, Y) # Horizontal stacking: In relation to horizontal combo # Dstack: Stacked by depth print numpy.split (x,2,axis=0) # Split by row [Array ([[[1, 2, 3]]), Array ([[[4, 5, 6])]print NUMPY.S Plit (X,3,axis=1) # Split by column [Array ([[[1],[4]]), Array ([[[2],[5]]), Array ([[[3],[6]])]# stack auxiliary class import numpy as Nparr = Np.arange (6)          arr1 = Arr.reshape ((3, 2)) arr2 = Np.random.randn (3, 2) print ' R_ used to stack by rows ' Print np.r_[arr1, arr2] ' [[0.          1.] [2.          3.] [4. 5.] [0.22621904 0.39719794] [ -1.2201912-0.23623549] [ -0.83229114-0.72678578]] ' print ' c_ used to stack by column ' Print Np.c_[n          P.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 ' Slice directly to array ' Print Np.c_[1:6, -10:-5] ' [[1-10] [2-9] [3-8] [4-7] [5-6]] '
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
16, the elements of the array repeat operation

code example:

print ‘数组的元素重复操作‘x = numpy.array([[1,2],[3,4]])print x.repeat(2) # 按元素重复 [1 1 2 2 3 3 4 4]print x.repeat(2,axis=0) # 按行重复 [[1 2][1 2][3 4][3 4]]print x.repeat(2,axis=1) # 按列重复 [[1 1 2 2][3 3 4 4]]x = numpy.array([1,2])print numpy.tile(x,2) # tile瓦片:[1 2 1 2]print numpy.tile(x, (2, 2))  # 指定从低维到高维依次复制的次数。 # [[1 2 1 2][1 2 1 2]]

Basic use of Python's 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.