In the NumPy package we can use arrays to represent vectors, matrices, and higher-order data structures
First import the NumPy package:
From NumPy import*
There are several ways to initialize an NumPy array, such as
1.python list or meta-ancestor
2. Using the Arrange,linspace function
3. Reading data from a file
Example: List generation NumPy array:
V=array ([1,2,3,4])
M=array ([[1,2],[3,4]])
The V and M objects are the Ndarray types provided by the NumPy module
The difference between the v,m is that they have different dimensions.
They can get their dimensions through Ndarray.shape.
Ndarray.size get their number of elements
Example: M.shape m.size
You can also use shape (m) and size (m)
So why not use list?
Define element types that can be displayed by using the Dtype keyword when creating an array
Using array generation functions
X=arange (0,10,1) 0 to 10 pitch 1
Linspace (0,10,25) 0 to 101 of 25 total data
X,y=mgrid[0:5,0:5]
To generate a random array:
From NumPy import random
Random.rand (5,5) generates 5*5 matrix with random values from 0 to 1
RANDOM.RANDN (5,5) random value
Zeros ((3,3)) 3*3 0 matrix
Ones ((3,3)) 3*3 is a matrix of 1
File I/O creates an array:
CSV is a commonly used data format file type, using the Numpy.genfromtxt function to read
Use Numpy.savetxt to store an array in a CSV file
M=random.rand (3,3)
Savetxt ("Random-maxtrix.csv", M)
Nnmpy Native File type:
Save and read with Numpy.save and Numpy.load
Save ("Numpy.npy", M)
Load ("Numpy.npy")
Manipulating arrays:
Use square brackets:
M[1]
m[1,1]
If it is an n-dimensional array, omitting an index value during retrieval returns a whole row
M[1]
Use: can achieve the same effect.
M[1,:] One row m[:,1] a column
You can also use index values to assign values
A[1:3] will return 1th, Element 2nd---------Index This block is actually the same as the list.
A negative index is calculated from the end of the array. M[-1] The number of the first to count
The index tiles are the same in a two-dimensional array.
NumPy function
where function can convert an index mask to an indexed position
diag function extracts array diagonal lines
The take function is similar to the Advanced index usage
Choose Select multiple arrays to form a new array
When we subtraction between matrices, the default behavior is multiply-by-item
Matrix and matrix using dot function, multiplication of vectors
To map an array object to a matrix type
Python NumPy Package