1. The basic use of NumPy covers the following:
- Data type
Array type
Type Conversion
Create Array
Array Index
Array slices
Change Dimension
2. NumPy array object:
The ndarray in NumPy is a multidimensional array object, and the redemption consists of two parts:
- Actual data
The metadata describing the data.
Most array operations modify only the metadata part without changing the underlying actual data (a shallow copy understanding).
ndarray supports higher dimensions because arrays are generally homogeneous, so all element types of arrays must be consistent.
The subscripts of NumPy arrays, like Python, start at 0.
2.1 numpy.arange() creates arrays and numpy.array() creates vectors:
dtype:
import numpy as np a = np.arange(5) print(a.dtype)
Arnge (start, end, dtype)
dtype returns the data type, where int32 or int64 is returned
shape:
import numpy as np a = np.array([0,1,2,3,4]) print(a.shape) (5,)
We use shape s to return the dimension of a vector, where there are five rows, the column is empty, and the return value is tuple type.
2.2 Create multidimensional arrays:
import numpy as np a = np.array([np.arange(2),np.arange(2)]) print(a) #[[0 1] # [0 1]] print(a.shape) #(2, 2)
We create a 2*2 multidimensional array by passing the array created by the arange function as a vector/list element and the list as a parameter to the array function.
2.3 Select array elements:
Sometimes we need to pick a particular element in an array.Love Treasure starts with 0
import numpy as np a = np.array([[1,2],[3,4]]) print(a) #[[1 2] # [3 4]] print(a[0,0]) #1 print(a[1,1]) #4
We found that the entire array must have a large bracket wrapped around its contents.
2.4 Data type:
a = np.array([[1,2],[3,4]],dtype='f')
Some of these types of data can be found.You can also specify a complex array.
2.5 Custom data type and dtype class properties:
View bytes occupied:
itemsize
import numpy as np a = np.array([[1,2],[3,4]],dtype='f') print(a.dtype.itemsize) #4
Custom data types use dtype and then call:
import numpy as np t = np.dtype([('name',str,40),('numitems',int),('price',float)]) print(t) #[('name', '<U40'), ('numitems', '<i4'), ('price', '<f8')] print(t['name']) #<U40 itemz = np.array([('Meaning of life DVD',42,3.14),('Butter',13,2.72)],dtype=t) print(itemz[1]) #('Butter', 13, 2.72)
Indexes and slices of 2.6 one-dimensional arrays:
import numpy as np a = np.arange(9) print(a) #[0 1 2 3 4 5 6 7 8] print(a[3:7]) #[3 4 5 6] print(a[:7:2]) #[0 2 4 6] print(a[::-1]) #[8 7 6 5 4 3 2 1 0]
We found this to be the same as the index and slice of the Python list.
Tiles and indexes of 2.7 multidimensional arrays:
reshape: Represents three-dimensional coordinates to select any one, that is, floor, row, column number
import numpy as np b0 = np.arange(24) print(b0) #[ 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 = np.arange(24).reshape(2,3,4) print(b) #[[[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # # [[12 13 14 15] # [16 17 18 19] # [20 21 22 23]]] print(b.shape) #(2, 3, 4) print(b[:,0,0]) #[ 0 12]
2.8 Change the dimension of the array:
reshape(a,newshape,order='C')
Where:
a: Array - the data to be processed.
newshape: The new format - integer or array (2,3) represents 2 rows and 3 columns.The new shape should be financial to the original shape.
order: The situation is a bit more complicated than the first two parameters, which will be explained in a larger space and an easier example will be given later.
"C" refers to the elements in the read/index order written in class C, with the last dimension changing the fastest and the first dimension changing the slowest.Take a two-dimensional array as an example. Simply put, it reads horizontally, writes horizontally, and reads/writes a line first.
"F" refers to reading/writing elements in FORTRAN class index order, with the last dimension changing the slowest and the first dimension changing the fastest.Read vertically, write vertically, read/write a column first.Note that the "C" and "F" options do not take into account the memory layout of the underlying array and only refer to the order of the indexes.
The effect of the array generated by the "A" option is related to the way the data of the original array A is stored. If the data is stored according to FORTRAN, it will have the same effect as "F", otherwise it will have the same effect as "C".It may sound a little fuzzy here, but here's an example.
Note: FORTRAN and C are two languages. They store arrays differently. FORTRSAN has limited columns and C has row precedence.The default array in python is stored as C when it is generated.However, many times we need to call some of Fortran's libraries for mathematical calculations, so we need to make the array generated by numpy stored as FORTRAN.
import numpy as np b0 = np.arange(4) print(b0) #[0 1 2 3] b1 = b0.reshape((2,2)) print(b1) #[[0 1] # [2 3]] b2 = np.arange(8) b3 = b2.reshape(2,2,2) print(b3) #[[[0 1] # [2 3]] # # [[4 5] # [6 7]]]
ravel:
Flatten the matrix:
import numpy as np b0 = np.array([np.arange(2),np.arange(2)]) print(b0) # #[[0 1] # [0 1]] print(b0.ravel()) #[0 1 0 1]
flatten:
... is also a flattening operation, the same as the ravel function.However, the flatten function requests memory allocation to report errors, and the ravelfunction knowledge returns a view of the array.
resize:
Like the reshaple function tweezers, hot death directly modifies the array of lock operations.
transpose:
Transpose operation, an operation of an array:
import numpy as np b0 = np.array([np.arange(2),np.arange(2)]) print(b0) # #[[0 1] # [0 1]] print(b0.transpose()) #[[0 0] # [1 1]]
Combination of 2.9 arrays:
vstack:
- Vertical combination
import numpy as np a = np.arange(9).reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] b = 2 * a print(b) #[[ 0 2 4] # [ 6 8 10] # [12 14 16]] print(np.vstack((a,b))) #[[ 0 1 2] # [ 3 4 5] # [ 6 7 8] # [ 0 2 4] # [ 6 8 10] # [12 14 16]]
dstack:
Depth combination: A series of arrays are cascaded along the vertical axis (depth).For example, there are several image lattice data in a two-dimensional plane, which we can talk about overlapping along the vertical axis to explain what depth combination is.
import numpy as np a = np.arange(9).reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] b = 2 * a print(b) #[[ 0 2 4] # [ 6 8 10] # [12 14 16]] print(np.dstack((a,b))) #[[[ 0 0] # [ 1 2] # [ 2 4]] # # [[ 3 6] # [ 4 8] # [ 5 10]] # # [[ 6 12] # [ 7 14] # [ 8 16]]]
hstack:
Horizontal combination
import numpy as np a = np.arange(9).reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] b = 2 * a print(b) #[[ 0 2 4] # [ 6 8 10] # [12 14 16]] print(np.hstack((a,b))) #[[ 0 1 2 0 2 4] # [ 3 4 5 6 8 10] # [ 6 7 8 12 14 16]]
colum_stack:
Column Combination: The column_stack function combines one-dimensional arrays in column direction.
import numpy as np # One-dimensional array oned = np.arange(2) print(oned) #[0 1] twice_oned = 2 * oned print(twice_oned) #[0 2] print(np.column_stack((oned,twice_oned))) #[[0 0] # [1 2]] # Two-dimensional array: For two-dimensional array column_stack, hstack has the same effect.
row_stack:
Line combination: For two arrays that are considered to be minorities, they are directly cascaded together to form a two-dimensional array.
concatenate:
This has the same effect as hstack.
Split the 2.10 array:
hsplit:
Horizontal Division
import numpy as np a = np.arange(9) a = a.reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] # Divide horizontally into three subarrays of the same size print(np.hsplit(a,3)) #[array([[0], # [3], # [6]]), #array([[1], # [4], # [7]]), #array([[2], # [5], # [8]])]
vsplit:
- Vertical division:
dsplit:
Depth Division:
split:
Default Split
print(np.split(a,3,axis=1))
1 = Vertical, 0 = Horizontal
Attributes of the 2.11 array:
ndim property, giving the dimension of the array or the number of array axes
The size property, which gives the total number of array elements
The itemsize property gives the number of bytes in memory that elements in an array occupy
Real property, giving the real part
image property, giving the imaginary part
The flat property returns a numpy.flatiter object, which is the only way to get the flatiter object, and we cannot access the flatiter's constructor.This so-called "flat iterator" allows us to traverse any multidimensional array just like a one-dimensional array.
Conversion of 2.12 arrays:
tolist:
Convert numpy array format to python list mode
import numpy as np a = np.arange(9).reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] b = a.tolist() print(b,type(b)) # [6 7 8]] #[[0, 1, 2], [3, 4, 5], [6, 7, 8]] <class 'list'>
Operations on 2.13 arrays:
Addition, Subtraction, Multiplication and Division
transpose:
Inverse matrix: linalg.inv()
import numpy as np a = np.arange(9).reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] b = np.linalg.pinv(a) print(b) #[[-5.55555556e-01 -1.66666667e-01 2.22222222e-01] # [-5.55555556e-02 2.01227923e-16 5.55555556e-02] # [ 4.44444444e-01 1.66666667e-01 -1.11111111e-01]]
- Diagonal matrix:eye
a = np.arange(9).reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] b = np.eye(9,9) print(b) #[[1. 0. 0. 0. 0. 0. 0. 0. 0.] # [0. 1. 0. 0. 0. 0. 0. 0. 0.] # [0. 0. 1. 0. 0. 0. 0. 0. 0.] # [0. 0. 0. 1. 0. 0. 0. 0. 0.] # [0. 0. 0. 0. 1. 0. 0. 0. 0.] # [0. 0. 0. 0. 0. 1. 0. 0. 0.] # [0. 0. 0. 0. 0. 0. 1. 0. 0.] # [0. 0. 0. 0. 0. 0. 0. 1. 0.] # [0. 0. 0. 0. 0. 0. 0. 0. 1.]]
Zero Matrix: zeros
Empty Matrix: empty
Trigonometric Matrix: diag
import numpy as np a = np.arange(9).reshape(3,3) print(a) #[[0 1 2] # [3 4 5] # [6 7 8]] b = np.diag((1,2,3)) print(b) #[[1 0 0] # [0 2 0] # [0 0 3]]
Matrix function of 2.14 matrix library:
Matches must be two-dimensional, but numpy arrays (ndarrays can be multidimensional), and the main advantage of matrix is that it resembles the format in matlab and does not seem convenient to enclose in square brackets.But data in a matrix format is not ndarrays, and can also be transformed through tolist
import numpy as np a = np.mat('4 3;2 1') print(a) #[[4 3] # [2 1]] print(type(a)) #<class 'numpy.matrixlib.defmatrix.matrix'> b = a.tolist() print(b,type(b)) #[[4, 3], [2, 1]] <class 'list'>