Use of numpy library

The numpy library is a third-party library for processing multidimensional arrays (ndarrays) with the same elements.
import numpy as np
There are 7 commonly used functions for creating arrays (ndarray type) in the numpy library, as follows:
1) np.array([x, y, x], dtype=int) Create arrays from python lists and tuples;
2) np .arange(x, y, i) creates an array from x to y, with i as the step size;
3) np.linspace(x, y, n) creates an array from x to y, which is equally divided into n elements Array;
4) np.indices((m,n)) creates a matrix with m rows and n columns;
5) np.random.rand(m,n) creates a random array with m rows and n columns;
6) np.ones ((m,n),dtype) creates an array with m rows and n columns of all 1s, dtype is the data type;
7) np.empty((m,n),dtype) creates an array of m rows and n columns with all 0s, dtype is the data type;

After creating a simple array, you can view the basic properties of the ndarray class as follows:
1) ndarray.ndim the number of axes of the array, also known as the rank;
2) ndarray.shape the integer size of the array in each dimension tuple;
3) ndarray.size the total number of array elements;
4) ndarray.dtype the data type of the array elements;
5) ndarray.itemsize the data type of each element in the array, the dtype type can be used to create an array;
6) ndarray.data contains buffer addresses of actual array elements;
7) ndarray.flat iterators of array elements.

Shape operation methods of the ndarray class (5 in total):
1) ndarray.reshape(n,m) returns an array of dimension (n,m) without changing the array ndarray;
2) ndarray.resize(new_shape) and reshape( ) has the same effect, directly modifying the array ndarray;
3) ndarray.swapaxes(ax1,ax2) Swap any two dimensions of the n dimensions of the array;
4) ndarray.flatten() Reduce the dimension of the array and return a folded One-dimensional arrays;
5) ndarray.ravel() works the same as np.flatten(), but returns a view of the array.

Calculate the mean of a matrix using the numpy library:

>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a) # 将上面二维矩阵的每个元素相加除以元素个数(求平均数)
2.5
>>> np.mean(a, axis=0) # axis=0,计算每一列的均值
array([ 2.,  3.])
>>> np.mean(a, axis=1) # 计算每一行的均值
array([ 1.5,  3.5])

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325395729&siteId=291194637