[Reprint] Use of numpy library in python

Reference link: numpy.amin in Python

dtype = dt) print(a) output is [(10,) (20,) (30,)] The type field name can be used to access the actual age column import numpy as np dt = np.dtype([('age ',np.int8)]) a = np.array([(10,),(20,),(30,)], dtype = dt) print(a['age']) You can take out the array a The age column student = np.dtype([('name','S20'), ('age','i1'), ('marks','f4')]) print(student) [('name' ,'S20'), ('age','i1'), ('marks','f4')] import numpy as np student = np.dtype([('name','S20'), ('age ','i1'), ('marks','f4')]) a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) print(a) [('abc', 21, 50.0), ('xyz', 18, 75.0)] Each built-in type has a unique corresponding character code, as follows: b Boolean i (signed) integer Type u Unsigned integer type integer f Floating point type c Complex number floating point type m timedelta (time interval) M datetime (date time) O (Python) Object S, a (byte-) String U Unicode V Raw data (void) Axis is the dimension and axis in numpy, axis=0 is to operate on each column, and axis is to operate on each row. Property description ndarray.ndim rank, that is, the number of axes or the number of dimensions. ndarray.shape The dimensions of the array. For a matrix, the total number of array elements with n rows and m columns ndarray.size is equivalent to the value of n*m in .shape ndarray . dtype The element type of the ndarray object ndarray.itemsize The size of each element in the ndarray object in bytes ndarray.flags The memory information of the ndarray object ndarray.real The real part of the ndarray element ndarray.imag The imaginary part of the ndarray element ndarray.data The buffer containing the actual array elements. Since the elements are generally obtained by the index of the array, this attribute is usually not needed. a = np.arange(24) print (a.ndim) # a now has only one dimension b = a.reshape(2,4,3) # b now has three dimensions a is 0 to 23 and the numbers increase by 1 change After the shape is array([[[ 0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]], [[12, 13, 14], [ 15, 16, 17], [18, 19, 20], [21, 22, 23]]]) is first divided into 2 and then divided into 3, there are 3 elements in a one-dimensional array, shape represents the dimension of this array b.shape = (2, 4, 3) And the size and shape of the array can be changed by shape and reshape. b.shape= (4,6) b array([[ 0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]]) or b.reshape(3,8) b.reshape(3,8) array([[ 0, 1, 2, 3, 4 , 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23]]) b.itemsize returns every The size of the value of each element b. flags returns the memory information of the array, including the following attributes: C_CONTIGUOUS © data is in a single C-style continuous segment F_CONTIGUOUS (F) data is in a single Fortran-style continuous segment OWNDATA (O) array has its all The used memory or borrow it from another object WRITEABLE (W) The data area can be written, set the value to False, the data is read-only ALIGNED (A) Data and all elements are properly aligned to the hardware UPDATEIFCOPY (U) This array is a copy of other arrays. When this array is released, the contents of the original array will be updated. b = np.empty([size],dtype=...) In the same way, an array of all 1s can be created or An array of all 1s//The default is a floating point number, but the element type can be set, such as np.int or a custom type dtype=[('x','i4'),('y','i4')] numpy Create an array from an existing array numpy.asarray(a, dtype = None, order = None) a Input parameters of any form, can be, list, tuple of list, tuple, tuple of tuple, list of tuple , Multidimensional array dtype data type, optional order is optional, there are two options "C" and "F", which represent, row-first and column-first, the order of storage elements in computer memory. numpy.fromiter can create an ndarray object in an iterable object and returns a one-dimensional array numpy.fromiter(iterable,dtype,count=-1) iterable iterable object dtype returns the data type of the array count The number of data read, the default is- 1. Read all data 'i4')] numpy creates an array from an existing array numpy.asarray(a, dtype = None, order = None) a Input parameters of any form, which can be lists, tuples of lists, tuples, elements of tuples List of groups, tuples, multidimensional array dtype data type, optional order is optional, there are two options "C" and "F", which represent, row-first and column-first, the order of storage elements in computer memory. numpy.fromiter can create an ndarray object in an iterable object and returns a one-dimensional array numpy.fromiter(iterable,dtype,count=-1) iterable iterable object dtype returns the data type of the array count The number of data read, the default is- 1. Read all data 'i4')] numpy creates an array from an existing array numpy.asarray(a, dtype = None, order = None) a Input parameters of any form, which can be lists, tuples of lists, tuples, elements of tuples List of groups, tuples, multidimensional array dtype data type, optional order is optional, there are two options "C" and "F", which represent, row-first and column-first, the order of storage elements in computer memory. numpy.fromiter can create an ndarray object in an iterable object and returns a one-dimensional array numpy.fromiter(iterable,dtype,count=-1) iterable iterable object dtype returns the data type of the array count The number of data read, the default is- 1. Read all data 

list=range(5)

>>> it=iter(list)

>>> it

<range_iterator object at 0x000001CAE9215DD0>

>>> x=np.fromiter(it,float)

>>> x

array([0., 1., 2., 3., 4.])

 

numpy.arange(start,stop,step,dtype) numpy.linspace creates a one-dimensional array and is an arithmetic sequence of np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype= None) The start value of start sequence stop The end value of the sequence, if endpoint is true, this value is included in the number of samples of equal step size to be generated in num in the sequence, the default is 50 endpoint When the value is true, the sequence contains stop Value, if not included, the default is True. If retstep is True, the spacing will be displayed in the generated array, otherwise it will not be displayed. dtype ndarray data type 

>>>a = np.linspace(1,3,23,True,True)

>>> a

(array([1.        , 1.09090909, 1.18181818, 1.27272727, 1.36363636,

       1.45454545, 1.54545455, 1.63636364, 1.72727273, 1.81818182,

       1.90909091, 2.        , 2.09090909, 2.18181818, 2.27272727,

       2.36363636, 2.45454545, 2.54545455, 2.63636364, 2.72727273,

       2.81818182, 2.90909091, 3.        ]), 0.09090909090909091)

>>> 

 

It can be seen that this is an arithmetic sequence, and the last item is the step size numpy.logspace function is used to create a geometric sequence. The format is as follows: np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None) 

>>> a = np.logspace(1,2,10)

>>> a

array([ 10.        ,  12.91549665,  16.68100537,  21.5443469 ,

        27.82559402,  35.93813664,  46.41588834,  59.94842503,

        77.42636827, 100.        ])

>>> a = np.logspace(0,5,10,base = 2)

>>> a

array([ 1.        ,  1.46973449,  2.16011948,  3.1748021 ,  4.66611616,

        6.85795186, 10.0793684 , 14.8139954 , 21.77264   , 32.        ])

>>> 

 

Numpy slice and index slice can use the built-in slice function and set the start, stop and step parameters to cut a new array from the original array. 

>>> a = np.arange(10)

>>> s=slice(2,8,3)

>>> a[s]

array([2, 5])

>>> b = a[2:8:3]

>>> b

array([2, 5])

 

There are also the following indexing methods: 

>>> a = np.array([[1,2,3],[2,2,2],[1,8,9]])

>>> print(a[...,1])

[2 2 8]

>>> print(a[1,...])

[2 2 2]

>>> print(a[1:,...])

[[2 2 2]

 [1 8 9]]

>>> print(a[...,1:])

[[2 3]

 [2 2]

 [8 9]]

 

According to the matrix, it is obvious that these indexes are different. Integer array index: 

>>> x=np.array([[1,2],[3,4],[5,6]])

>>> y = x[[0,1,2],[0,1,1]]

>>> y

array([1, 4, 6])

 

This is divided into row index and column index, which means to find the Boolean index of the element at (0,0)(1,1)(2,1): 

>>> x=np.array([[1,2],[3,4],[5,6]])

>>>> print(x[x>3])

[4 5 6]

 

Or you can use ~ to indicate not, for example: 

>>> a = np.array([np.nan,1,2,np.nan,3,4,5])

>>> print(~np.isnan(a))

[False  True  True False  True  True  True]

>>> print(a[~np.isnan(a)])

[1. 2. 3. 4. 5.]

 

You can also filter plurals: 

>>> a = np.array([1, 2+1j ,3,9j])

>>> print(a[np.iscomplex(a)])

[2. + 1.j 0. + 9.j]

 

Fancy indexing refers to indexing using integer arrays, for example: 

>>> x

array([[ 0,  1,  2,  3],

       [ 4,  5,  6,  7],

       [ 8,  9, 10, 11],

       [12, 13, 14, 15],

       [16, 17, 18, 19],

       [20, 21, 22, 23],

       [24, 25, 26, 27],

       [28, 29, 30, 31]])

>>> print(x[[4,2,1,7]])

[[16 17 18 19]

 [ 8  9 10 11]

 [ 4  5  6  7]

 [28 29 30 31]]

 

 

Pass in the reverse index array, for example: 

>>> print(x[[-4,-2,-1,-7]])

[[16 17 18 19]

 [24 25 26 27]

 [28 29 30 31]

 [ 4  5  6  7]]

 

Pass in multiple index arrays (use np.ix_), for example: 

>>> print(x[np.ix_([1,5,7,2],[0,3,1,2])])

[[ 4  7  5  6]

 [20 23 21 22]

 [28 31 29 30]

 [ 8 11  9 10]]

 

ix_ produces a Cartesian product to get (1,0), (1,3), (1,1)... and so on. Numpy broadcasting is a way for numpy to perform numerical calculations on arrays of different shapes. E.g: 

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

>>> b = np.array([10,20,30,40])

>>> c =a * b

>>> c

array([ 10,  40,  90, 160])

 

When the two arrays have different shapes, numpy will automatically trigger the broadcast mechanism. E.g: 

>>> a = np.array([[ 0, 0, 0],

...            [10,10,10],

...            [20,20,20],

...            [30,30,30]])

>>> b = np.array([1,2,3])

>>> a+b

array([[ 1,  2,  3],

       [11, 12, 13],

       [21, 22, 23],

       [31, 32, 33]])

 

When the two cannot be added and subtracted normally, the broadcast mechanism will be triggered, which is equivalent to the following effects, for example: 

>>> bb=np.tile(b,(4,1))

>>> a+bb

array([[ 1,  2,  3],

       [11, 12, 13],

       [21, 22, 23],

       [31, 32, 33]])

 

The tile function is to copy the original matrix horizontally and vertically. tile(mat,(1,4)) copies the column to four times the original 

>>> np.tile(b,4)

array([1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])

>>> np.tile(b,(1,4))

array([[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]])

 

numpy iterating array can use numpy.nditer() to create an iterator, for example the following: 

>>> for x in np.nditer(bb):

...     print(x)

output = 1 2 3 1 2 3 1 2 3 1 2 3

 

The transposition traversal order of a and a is the same, and their storage data in the memory is also the same. Therefore, the iteration sequence is the same for both. But aTcopy(order ='C') defaults to row-wise access, which is different from the previous two storage methods. Or add order='C/F' to indicate row access or column access. There is an optional parameter op_flags to modify the value in the array. It is a read-only object by default, and it can be set to read-write or write-only. Using external loops, the constructor of the nditer class has multiple flags parameters, which can accept the following values: c_index can track the index of C order f_index The index multi-index that can track the Fortran order. Each iteration can track an index type external_loop. The value given is a one-dimensional array with multiple values, not a zero-dimensional array. For example, the following example: 

>>> for i in np.nditer(a, flags= ['external_loop'],order = 'F'):

...     print(i,end =',')

... 

[0 9],[ 3 12],[ 6 15],

 

Broadcast iteration: nditer can iterate two different arrays at the same time, for example, the following formula: 

>>> a = np.arange(0,60,5)

>>> a = a.reshape(3,4)

>>> a

array([[ 0,  5, 10, 15],

       [20, 25, 30, 35],

       [40, 45, 50, 55]])

>>> b = np.array([1,2,3,4],int)

>>> for x,y in np.nditer([a,b]):

...     print("%d:%d" % (x,y),end=",")

... 

0:1,5:2,10:3,15:4,20:1,25:2,30:3,35:4,40:1,45:2,50:3,55:4,

 

Numpy array operations: reshape modify the shape without changing the data flat, the array element iterator flatten returns a copy of the array, the modification of the copy will not affect the original array ravel returns the expanded array 

>>> a = np.arange(0,60,5)

>>> a

array([ 0,  5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55])

>>> a = a.reshape(3,4)

>>> a

array([[ 0,  5, 10, 15],

       [20, 25, 30, 35],

       [40, 45, 50, 55]])

>>> for i in a:

...     print(i)

... 

[ 0  5 10 15]

[20 25 30 35]

[40 45 50 55]

>>> for element in a.flat:

...     print(element)

... 

0

5

10

15

20

25

30

35

40

45

50

55

>>> np.ravel(a,'C')

array([ 0,  5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55])      

 

Flip the array: transpose swaps the dimensions of the array ndarray.T and self.transpose() are the same rollaxis scrolls the specified axis backwards swapaxes swaps the two axes of the array 

>>> np.transpose(a)

array([[ 0, 20, 40],

       [ 5, 25, 45],

       [10, 30, 50],

       [15, 35, 55]])

>>> a.T

array([[ 0, 20, 40],

       [ 5, 25, 45],

       [10, 30, 50],

       [15, 35, 55]])      

 

np.swapaxes(0,2), that is, axis 0 and axis 1 are swapped. For example, the first element arr[0,0,0] is still arr[0,0,0] after the exchange; the second element arr[0,0,1] is arr[1,0, after the exchange 0];...; The last element arr[1,1,2], after the exchange is arr[2,1,1]. 

>>> a

array([[[0, 1],

        [2, 3]],

 

       [[4, 5],

        [6, 7]]])

>>> np.swapaxes(a,2,0)

array([[[0, 4],

        [2, 6]],

 

       [[1, 5],

        [3, 7]]])

 

Numpy mathematical functions: Provides standard trigonometric functions, sin(), cos(), tan(). And the angle can be converted through np.pi/180. E.g: 

>>> a = np.array([0,30,45,60,90])

>>> print(np.sin(a*np.pi/180))

[0.         0.5        0.70710678 0.8660254  1.        ]

>>> inv = np.arcsin(0.5)

>>> np.degrees(inv)

30.000000000000004

 

Rounding function: The numpy.around() function returns the rounded value of the specified number. numpy.around(a,decimals) For example: 

>>> a = np.array([17.8, 11, 0, 5.55, 0.567, 25.532])

>>> np.around(a,1)

array([17.8, 11. ,  0. ,  5.6,  0.6, 25.5])

>>> np.around(a,0)

array([18., 11.,  0.,  6.,  1., 26.])

>>> np.around(a,-1)

array([20., 10.,  0., 10.,  0., 30.])

 

Round down, round up: numpy.floor() returns the largest integer less than or equal to the specified expression, that is, round down. numpy.ceil() returns the smallest integer greater than or equal to the specified expression, that is, rounded up. E.g: 

>>> np.floor(a)

array([-2.,  1., -1.,  0., 10.])

>>> np.ceil(a)

array([-1.,  2., -0.,  1., 10.])

 

Numpy arithmetic functions: NumPy arithmetic functions include simple addition, subtraction, multiplication and division: add(), subtract(), multiply() and divide(). 

Note that the arrays must have the same shape or conform to the array broadcasting rules. E.g: 

>>> a = np.arange(9, dtype=np.float_).reshape(3,3)

>>> a

array([[0., 1., 2.],

       [3., 4., 5.],

       [6., 7., 8.]])

>>> b = np.array([10,10,10])

>>> np.add(a,b)

array([[10., 11., 12.],

       [13., 14., 15.],

       [16., 17., 18.]])

>>> np.subtract(a,b)

array([[-10.,  -9.,  -8.],

       [ -7.,  -6.,  -5.],

       [ -4.,  -3.,  -2.]])

>>> np.subtract(b,a)

array([[10.,  9.,  8.],

       [ 7.,  6.,  5.],

       [ 4.,  3.,  2.]])

>>> np.multiply(a,b)

array([[ 0., 10., 20.],

       [30., 40., 50.],

       [60., 70., 80.]])

>>> np.divide(a,b)

array([[0. , 0.1, 0.2],

       [0.3, 0.4, 0.5],

       [0.6, 0.7, 0.8]])

 

The numpy.reciprocal() function returns the element-wise reciprocal of the parameter. For example, 1/4 counts down to 4/1. 

>>> np.reciprocal([0.25,1.33])

array([4.       , 0.7518797])

 

The numpy.power() function takes the element in the first input array as the base and calculates its power to the corresponding element in the second input array. E.g: 

>>> a = np.array([10,4,5])

>>> b = np.array([1,2,3])

>>> np.power(a,b)

array([ 10,  16, 125], dtype=int32)

 

But it must sign the condition of broadcasting, otherwise it will go wrong. 

>>> np.power(a,[1,2])

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: operands could not be broadcast together with shapes (3,) (2,) 

 

numpy.mod() calculates the remainder of the division of the corresponding elements in the input array. The function numpy.remainder() also produces the same result. E.g: 

>>> a = np.array([10,4,5])

>>> b = np.array([10,10,10])

>>> np.mod(a,b)

array([0, 4, 5], dtype=int32)

>>> np.mod(b,a)

array([0, 2, 0], dtype=int32)

 

numpy statistical function: numpy.amin() is used to calculate the minimum value of the elements in the array along the specified axis. 

numpy.amax() is used to calculate the maximum value of the elements in the array along the specified axis. E.g: 

>>> a

array([[3, 7, 5],

       [8, 4, 3],

       [2, 4, 9]])

>>> np.amin(a,1)

array([3, 3, 2])

>>> np.amin(a,0)

array([2, 4, 3])

>>> np.amax(a,0)

array([8, 7, 9])

>>> np.amax(a,1)

array([7, 8, 9])

 

The numpy.ptp() function calculates the difference between the maximum value and the minimum value (maximum-minimum) of elements in the array. 

>>> a

array([[3, 7, 5],

       [8, 4, 3],

       [2, 4, 9]])

>>> np.ptp(a)

7

>>> np.ptp(a,1)

array([4, 5, 7])

>>> np.ptp(a,0)

array([6, 3, 6])

 

Standard deviation: np.std([1,2,3,4]) 

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

1.118033988749895

 

Variance: np.var([1,2,3,4]) 

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

1.25

 

numpy sorting speed worst case work space stability'quicksort' (quick sort) 1 O(n^2) 0 No'mergesort' (merge sort) 2 O(nlog(n)) ~n/2 Yes'heapsort' (Heap sort) 3 O(nlog(n)) 0 No The numpy.sort() function returns a sorted copy of the input array. The function format is as follows: numpy.sort(a, axis, kind, order) The numpy.argsort() function returns the index value of the array value from small to large. Numpy linear algebra: dot The dot product of two arrays, that is, the corresponding elements are multiplied. vdot The dot product of two vectors inner product of two arrays matmul The matrix product of two arrays determine the determinant of the array solve the linear matrix equation inv Calculate the multiplication of the matrix The inner product of the matrix is ​​the product of the corresponding position. constant. E.g: 

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

>>> b = np.array([[11,12],[13,14]])

>>> np.dot(a,b)

array([[37, 40],

       [85, 92]])

 

The calculation formula is: 

[[111+213, 112+214],[311+413, 312+414]] The numpy.vdot() function is the dot product of two vectors. If the first parameter is a complex number, then its conjugate complex number will be used in the calculation. If the parameter is a multidimensional array, it will be expanded. E.g: 

>>> np.vdot(a,b)

130

 

The calculation formula is: 111 + 212 + 313 + 414 = 130 The numpy.inner() function returns the vector inner product of a one-dimensional array. For higher dimensions, it returns the product of the sum on the last axis. For example: The numpy.matmul function returns the matrix product of two arrays. Although it returns the normal product of a two-dimensional array, if the dimension of any parameter is greater than 2, it will be treated as a stack of matrices existing in the last two indexes and broadcast accordingly. 

On the other hand, if any parameter is a one-dimensional array, it is promoted to a matrix by appending 1 to its dimension and removed after the multiplication. 

For a two-dimensional array, it is matrix multiplication: 

>>> a = [[1,0],[0,1]]

>>> b = [[2,3],[1,4]]

>>> np.matmul(a,b)

array([[2, 3],

       [1, 4]])

 

The numpy.linalg.det() function calculates the determinant of the input matrix. E.g: 

>>> np.linalg.det(a)

1.0

 

The numpy.linalg.inv() function calculates the multiplicative inverse matrix of a matrix. E.g: 

>>> a = [[1,0],[0,1]]

>>> np.linalg.inv(a)

array([[1., 0.],

       [0., 1.]])

 

Matplotlib is a plotting library for Python. It can be used with NumPy and provides an effective open source alternative to MatLab. It can also be used with graphics toolkits such as PyQt and wxPython. For example, the following use: 

>>> from matplotlib import pyplot as plt

>>> x = np.arange(1,11)

>>> y = x * 2 +5

>>> plt.title("Demo")

Text(0.5,1,'Demo')

>>> plt.xlabel("x axis caption")

Text(0.5,0,'x axis caption')

>>> plt.ylabel("y axis caption")

Text(0,0.5,'y axis caption')

>>> plt.plot(x,y)

[<matplotlib.lines.Line2D object at 0x000001FB5EFB7FD0>]

>>> plt.show()

 

Shown as: The specific python data visualization needs to be supplemented by yourself, so I won't go into details here. Reference address: https://www.runoob.com/numpy/numpy-tutorial.html

Guess you like

Origin blog.csdn.net/u013946150/article/details/113102344