Common basic numpy operations and numpy operations

Source: Internet
Author: User

Common basic numpy operations and numpy operations

The dimension of the NumPy array is called rank. The rank of the one-dimensional array is 1, the rank of the Two-dimensional array is 2, and so on. In NumPy, each linear array is called an axis, and the rank is actually the number of axes. For example, a two-dimensional array is equivalent to a one-dimensional array, and each element in this one-dimensional array is a one-dimensional array. Therefore, this one-dimensional array is the axis (axes) in NumPy, and the number of axes-rank, is the dimension of the array.

1. Create a Matrix

The matrix module in the Numpy library is an ndarray object and has many attributes: T, data, dtype, flags, flat, imag, real, size,

Itemsize, nbytes, ndim, shape, strides, ctypes, base, and so on.

1.1 adopt ndarray object

Import numpy as np # introduce numpy library # create a one-dimensional narray object a = np. array ([1, 2, 3, 4, 5]) # create a two-dimensional narray object a2 = np. array ([[, 5], [, 10]) # create a multi-dimensional object and so on

1.2 create a matrix using functions

1.2.1 arange

Import numpy as npa = np. arange (10) # The default value ranges from 0 to 10 (excluding 10). The step size is 1 print () # Return [0 1 2 3 4 5 6 7 8 9] a1 = np. arange (5, 10) # from 5 to 10 (excluding 10), step 1 print (a1) # Return [5 6 7 8 9] a2 = np. arange (5, 20, 2) # from 5 to 20 (excluding 20), step 2 print (a2) # Return [5 7 9 11 13 15 17 19]

1.2.2 linspace

Linspace () is similar to the linspace of matlab. It is used to create a sequence with a specified number of intervals and generate an equality sequence.

Import numpy as npa = np. linspace (, 5) # generate the first 0, the last 10, containing 5 numbers of the same number of print ()

1.2.3 logspace


Linspace is used to generate an equal-difference series, while logspace is used to generate an equal-ratio series.

The following example is used to generate an proportional series with the first digit being 100 and the last digit being 102, containing five numbers.

import numpy as npa = np.logspace(0,2,5)print(a)

1.2.4 ones, zeros, eye, empty

Ones creates a full 1 Matrix
Zeros creates a full 0 Matrix
Create an eye unit matrix
Empty creates an empty matrix (with actual values)

Import numpy as npa_ones = np. ones (3, 4) # create a 3*4 full 1 matrix print (a_ones) # result [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] a_zeros = np. zeros (3, 4) # create a 3*4 full 0 matrix print (a_zeros) # result [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] a_eye = np. eye (3) # create a level 3 unit matrix print (a_eye) # result [1. 0. 0.] [0. 1. 0.] [0. 0. 1.] a_empty = np. empty (3, 4) # create a 3*4 empty matrix print (a_empty) # result [[1.78006111e-306-3.13259416e-294 4.71524461e-309 1.94257842e + 289] [Cost-309 bytes + 294 bytes-310 3.82265219e-297] [Cost-309 1.07034394e-296] + 183 6.88704255e-315]

1.2.5 fromstring

The fromstring () method can convert a string into an ndarray object. This method is useful when you need to digitize a string to obtain the string's ascii code sequence.

A = "abcdef" B = np. fromstring (a, dtype = np. int8) # Because one character is 8 characters, dtype is specified as np. int8print (B) # Return [97 98 99 100 101 102]

1.2.6 fromfunction

The fromfunction () method generates matrix elements based on the row number and column number of the matrix.

For example, to create a matrix, each element in the matrix is the sum of the row number and column number.

Import numpy as npdef func (I, j): return I + ja = np. fromfunction (func, (5, 6) # The first parameter is the specified function, and the second parameter is the list or tuple, indicating the size of the matrix print (a) # Returns [0. 1. 2. 3. 4. 5.] [1. 2. 3. 4. 5. 6.] [2. 3. 4. 5. 6. 7.] [3. 4. 5. 6. 7. 8.] [4. 5. 6. 7. 8. 9.] # note that the column numbers of the row numbers start from 0.

2. Matrix Operations

The ndarray object in numpy overload many operators. Using these operators, you can perform operations on the corresponding elements between matrices.

For example, +,-, *,/, % ,**

2.1 Matrix Function operations

2.1.1 common mathematical operations (import numpy module: import numpy as np)

Matrix Functions Description
Np. sin () Returns the sine, sin (x) for each element in matrix)
Np. cos () Returns the cosine, cos (x) for each element in matrix)
Np. tan () Returns the tangent of each element in matrix a, tan (x)
Np. arcsin () Returns the arcsin (x) to every element in matrix)
Np. arccos () Returns the arccos (x) of each element in matrix)
Np. arctan () Returns an arc tangent to each element in matrix a. arctan (x)
Np. exp () Returns an exponential function for each element in matrix.
Np. sqrt () Root number of each element in matrix a √ x

For example, calculate the sin value of each element in the matrix.

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (np. sin (array) # result #[[0.84147098 0.90929743 0.14112001] # [-0.7568025-0.95892427-0.2794155]

2.1.2 matrix multiplication (DOT multiplication)

Matrix Multiplication must meet the conditions of matrix multiplication, that is, the number of columns in the first matrix is equal to the number of rows in the second matrix.

The matrix multiplication function is dot.

Import numpy as npa1 = np. array ([[, 3], [, 6]) # a1 is a 2*3 matrix a2 = np. array ([[1, 2], [3, 4], [5, 6]) # a2 is 3*2 matrix print (a1.shape [1] = a2.shape [0]) # True, print (a1.dot (a2) # a1.dot (a2) equivalent to a1 * a2 # in matlab, a1 * a2 in python is equivalent to a1. * a2 # in matlab. Result [22 28] [49 64]

2.1.3 transpose (transpose or T) of the matrix)

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (array. transpose () # or np. transpose (array) print (array. t) # result #[1 4] #[2 5] #[3 6] # transpose works the same as T #[[1 4] #[2 5] #[3 6]

2.1.4 inverse of the matrix

The inverse of the matrix needs to be first imported into numpy. linalg, And the inverse is obtained using the inv function of linalg.

The condition for matrix inversion is that the number of rows in the matrix is the same as the number of columns.

Import numpy as npimport numpy. linalg as lga = np. array ([[1, 2, 3], [4, 5, 6], [7, 8, 9]) print (lg. inv ()) # result [[-4.50359963e + 15 9.00719925e + 15-4.50359963e + 15] [hour + 15-hour + 16 9.00719925e + 15] [-hour + 15 9.00719925e + 15-4.50359963e +] a = np. eye (3) # print (lg. inv (a) # the inverse of the unit matrix is itself # result [1. 0. 0.] [0. 1. 0.] [0. 0. 1.]

2.1.5 maximum and minimum values

The maximum and minimum values of elements in a matrix are max and min, respectively. The maximum and minimum values of the entire matrix, row, or column are obtained.

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (array. max () # The result is 6 print (array. min () # The result is 1 # You can also specify the axis keyword to obtain the maximum and minimum print (array. max (axis = 0) # The maximum value of the X axis. 0 and 1 represent the rows and columns respectively.

2.1.6 Average Value

You can use the mean () or average () function to obtain the average value of elements in a matrix (). Similarly, the average value of the entire matrix, row, or column can be obtained.

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (array. mean () # The result is 3.5 print (np. average (array) # The result is 3.5 print (array. mean (axis = 0) # The average value in the row direction. Similarly, 0 and 1 represent the dimension.

2.1.7 variance

The variance function is var (), and the variance function var () is equivalent to the mean (abs (x-x. mean () *** 2), where x is the matrix.

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (array. var () # The result is 2.91666666667 # You can also use axis to specify Dimension 0, 1 to represent the row and column, print (array. var (axis = 0) # result #[2.25 2.25 2.25]

2.1.8 Standard Deviation

The standard deviation function is std ().

Std () is equivalent to sqrt (mean (abs (x-x. mean () ** 2), or sqrt (x. var ()).

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (array. std () # The result is 1.70782512766 # You can also use axis to specify Dimension 0, 1 to represent the row and column, print (array. std (axis = 0) # result #[1.5 1.5 1.5]

2.1.9 median or Median

The mean value refers to the value in the middle after the sequence is arranged in order of size. If there is an even number, it is the average value of the two numbers in the middle.

For example, the sequence [5, 2, 6, 4, 2] is arranged in the order of [2, 2, 4, 5, 6], and the number in the middle is 4, so the median value of this sequence is 4.

Another example is the sequence [5, 2, 6, 4, 3, 2] in order of size [2, 2, 3, 4, 5, 6]. Because there is an even number, the two numbers in the middle are 3 and 4, therefore, the median value in this sequence is 3.5.

The median () function calls numpy. median (x, [axis]). axis can specify the axis direction. The default value is axis = None.

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (np. median (array) # result: 3.5 # specify the Dimension print (np. median (array, axis = 0) # result #[2.5 3.5 4.5]

2.1.10 sum

The matrix summation function is sum (), which can sum rows, columns, or the entire matrix.

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (array. sum () # result: 21 # specify the Dimension print (array. sum (axis = 0) # result #[5 7 9]

2.1.11 sum and or sum

A location accumulates and refers to the sum of all elements before this location (including this location.

For example, for a sequence [1, 2, 3, 4, 5], the sum is [1, 3, 6, 10, 15], that is, the first element is 1, and the second element is 1 + 2 = 3, ......, The fifth element is 1 + 2 + 3 + 4 + 5 = 15.

The cumsum () function is used to calculate the sum of sums in the Matrix. You can perform sum on the rows, columns, or the entire matrix.

Import numpy as npa = np. array ([[1, 2, 3], [4, 5, 6]) print (. cumsum () # accumulate the entire matrix and # result [1 3 6 10 15 21] print (. cumsum (axis = 0) # accumulate the Row Direction and # result [[1 2 3] [5 7 9] print (. cumsum (axis = 1) # calculates the sum for the column direction and # result [[1 3 6] [4 9 15]

2.2 matrix Truncation

2.2.1 truncate by row and column

The matrix truncation is the same as the list. You can use [] (square brackets) to intercept the matrix.

Import numpy as npa = np. array ([[, 5], [, 10]) print (a []) # truncate the first line, returns [[1 2 3 4 5] print (a [1, 2: 5]) # truncates the second row, the third, fourth, and fifth columns, returns [8 9 10] print (a [1,:]) # truncates the second row and Returns [6, 8 9 10].

2.2.2 conditional Interception

Import numpy as npa = np. array ([[, 5], [, 10]) B = a [a> 6] # truncates elements larger than 6 in matrix, the range is one-dimensional array print (B) # Returns [7 8 9 10] # In fact, the Boolean statement first generates a Boolean matrix, passing the Boolean matrix into [] (square brackets) implement print (a> 6) # Return [[False] [False True]

When conditions are intercepted, the elements that meet certain conditions in the matrix become specific values.

For example, convert the element larger than 6 in the Matrix to 0.

Import numpy as npa = np. array ([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) print () # The start matrix is [[1 2 3 4 5] [6 7 8 9 10] a [a> 6] = 0 print () # After 6 is cleared, the matrix is [[1 2 3 4 5] [6 0 0 0]

2.2.3 clip Interception

Clip (matrix, min, max) # Return Value: All values smaller than min are equal to min, and all values greater than max are equal to max

Import numpy as nparray = np. array ([[1, 2, 3], [4, 5, 6]) print (array. clip (2, 4) # result #[2 2 3] #[4 4 4]

2.3 merge Matrices

The combination of matrices can be achieved through the hstack method and the vstack method in numpy.

Import numpy as npa1 = np. array ([[], []) a2 = np. array ([], []) #! Note that print (np. hstack ([a1, a2]) # merge horizontally. The returned results are as follows: [[1 2 5 6] [3 4 7 8] print (np. vstack (a1, a2) # merge vertically. The returned results are as follows: [1 2] [3 4] [5 6] [7 8]

You can also use the concatenatef method to merge matrices.

Np. concatenate (a1, a2), axis = 0) is equivalent to np. vstack (a1, a2 ))

Np. concatenate (a1, a2), axis = 1) is equivalent to np. hstack (a1, a2 ))

The common basic operation method of the numpy library above is all the content shared by the editor. I hope you can give us a reference and support the help house.

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.