numpy generate array

Numpy is an important scientific computing tool.
Through numpy, we can generate simulated data, such as randomly generating a number, and randomly generating a random number that obeys a normal distribution.
1.1 Create an array
Before performing mathematical operations, we must first create an array. There are two main ways to create arrays in Numpy:
(1) Create an array whose elements are 0 or 1.
(2) Convert existing data into an array, such as converting a list into an array.

1.1.1 Create an array

a. Use empty to generate random numbers,
pass in the shape parameter in the empty parameter to specify the shape of the generated array

import numpy as np
a=np.empty(shape=(3,3)) #创建一个3行3列的数组

b. The eye method creates an array whose diagonal elements are all 1s.
We can pass in parameter 3 to generate an array with three rows and three columns, all diagonal elements are 1s, and other elements are all 0s.

b=np.eye(3)

c. The identity method creates an identity matrix.
It feels similar to eye, but it can only create an identity matrix

np.identity(3)

np.identity(n, dtype=None)

np.eye(N, M=None, k=0, dtype=<type ‘float'>);

np.identity can only create square matrices

np.eye can create a rectangular matrix, and the k value can be adjusted. The position deviation of the diagonal is 1, 0 is centered, 1 deviates upward from 1, 2 deviates from 2, and so on, -1 deviates downward. If the absolute value of the value is too large, it will deviate, and the entire matrix will be all 0.

c. ones generates an array of all 1s

c=np.ones(shape=(2,4))#2行4列

d. zeros generates an array of all 0s

d=np.zeros(shape=(2,4))

e. The full method generates an array of specified numbers

e=np.full(shape=(3,3),fill_value=2)

1.1.2 Converting a list to an array

a=np.array([1,2,3])#生成数组

1.1.3 Generate a string of numbers

The form generated here is a list, we need to convert it to generate an array

a, arrange generates a sequence
similar to the range function

np.arrange(start=1,stop=10,step=2)#起始值为1,终止值为10,步长为2.

b. linespace generates a specified number of numbers within a fixed range

np.linspace(start=1,stop=10,num=5)#起始为1,终止为10,总共5个数

c. logspace uses log as the scale

np.logspace(start=1,stop=10,num=5)#

1.1.4 Generating special arrays

a. Generate diagonal matrix
Pass in the diagonal elements of the generated array, and the elements in other positions are all 0.

np.diag([1,2,3,4])#生成对角矩阵

b. Extract the diagonal matrix.
The array is passed in as a parameter. The method of diag is to extract the diagonal elements of the array.

np.diag([[1,2,3],
[4,5,6],
[7,8,9]])

c. Generate triangular matrix tri

np.tri(3,5)

d. Tril generates a triangular matrix based on the known matrix
. The first parameter is an array, and the second parameter is the relative position of the lower triangular matrix. -1 means to move down a not long

e, triu elevated triangular matrix

Guess you like

Origin blog.csdn.net/hmysn/article/details/127600723