Use of numpy in Python development

1. Pay attention to some points

Second, the use of numpy
1、 Create ndarray

1 Dimensional array a = np.array([1, 2, 3]) print(type(a), a.shape, a[0], a[1], a[2]) out:<class 'numpy.ndarray'> (3,) 1 2 3 # Re-assign a[0] = 5 print(a) out: [5 2 3] # 2-dimensional array b = np.array([[1,2,3],[4,5 ,6]]) print(b) out: [[1 2 3] [4 5 6]] print(b[0, 0], b[0, 1], b[1, 0]) out: 1 2 4

python

# Create a 2x2 array of all 0s
a = np.zeros((2,2))print(a)

out:[[0.0.][0.0.]]

 # Create a 1x2 array of all ones
b = np.ones((1,2))print(b)

out:[[1.1.]]

# Create a 2x2 array with a value of 7
c = np.full((2,2),7)print(c)

out:[[77][77]]

# Create a 2x2 identity matrix (diagonal elements are 1)
d = np.eye(2)print(d)

out:[[1.0.][0.1.]]

# Create a diagonal of 10,20,30,Diagonal matrix of 50
d_1 = np.diag([10,20,30,50])print(d_1)

out:[[10000][02000][00300][00050]]

# Create a one-dimensional 0-Array of 14
e = np.arange(15)print(e)

out:[01234567891011121314]

# Create a one-dimensional 4-Array of 9
e_1 = np.arange(4,10)print(e_1)

out:[456789]

# Create a one-dimensional 1-13 and an array with an interval of 3
e_2 = np.arange(1,14,3)print(e_2)

out:[1471013]

# Create a one-dimensional range at 0-10, an array of length 6
f = np.linspace(0,10,6)print(f)

out:
# The intervals of each element are equal, which is(10-0)/(6-1)=2. If you do not want to include the last 10, you can add the parameter endpoint= False
[0.,2.,4.,6.,8.,10.]  

# Convert the one-dimensional array created by arange into a two-dimensional array with 3 rows and 4 columns
g = np.arange(12).reshape(3,4)print(g)                        

out:
# Note: The amount of data before and after using reshape conversion should be the same, 12= 3x4
[[0,1,2,3],[4,5,6,7],[8,9,10,11]]              

# 2 x2 random array(matrix),The value range is[0.0,1.0)(Contains 0, does not contain 1)
h = np.random.random((2,2))print(e)

out:[[0.727769660.94164821][0.046526550.2316599]]

# Create a value range in[4,15), A random integer matrix with 2 rows and 2 columns
i = np.random.randint(4,15,size =(2,2))print(i)

out:[[6,5],[5,9]]

# Create a mean value of 0 and a standard deviation of 0.3x3 matrix randomly sampled from a normal distribution of 1
j = np.random.normal(0,0.1,size =(3,3))print(j)

out:[[-0.20783767,-0.12406401,-0.11775284],[0.02037018,0.02898423,-0.02548213],[-0.0149878,0.05277648,0.08332239]]
2、 Access & Change

python

# Visit a certain element, here you can try more by yourself
# To access an element of a one-dimensional array, fill in the index in the brackets
print(np.arange(6)[3]) 
out:3

# To access an element of a two-dimensional array, fill in the brackets[Row,Column]print(np.arange(6).reshape(3,2)[1,1]) 
out:3

# Access an element in a three-digit array, inside the brackets[Group, row, column]print(np.arange(12).reshape(2,3,2)[0,1,1]) 
out:3

# To change an element, use=Just assign and replace
a = np.arange(6)
a[3]=7      #Visit first, then reassign
print(a)[012745]
3、 delete#####

What needs to be noted here is the parameter of axis. In 2-dimensional data, axis = 0 means selecting rows, axis = 1 means selecting columns, but you cannot mechanically think that 0 means rows and 1 means columns. Note that in the premise of 2-dimensional data .

In 3D data, axis = 0 means group, 1 means row, and 2 means column. Why is this? As a reminder, how are the groups, rows, and columns sorted in the shape of a three-digit array?

== If you want to modify the value of a, you need to re-assign ==

python

a = np.arange(6).reshape(2,3)
np.delete(a,[0],axis =0)print(a)array([[0,1,2],[3,4,5]])  #The original data has not been changed

a = np.delete(a,[0],axis =0)  #Reassign
print(a)array([[3,4,5]])   #The original data has been changed
4、 Add to#####

The method of adding elements to ndarray is similar to python list. There are two commonly used methods:

python

The syntax is: np.append(ndarray, elements, axis)

python

The syntax is: np.insert(ndarray, index, elements, axis)

There is one more index in the parameter, which indicates the position to insert the new element.
5、 ndarray slice#####

python

a[:,:-1]Remove the last column
a[:,-1]Keep only the last column

python

Get the last column of data as a column:

a[:,3:]

out:array([[3],[7],[11],[15]])

python

Get the last column of data in the form of a one-dimensional array:

a[:,-1]

out:array([3,7,11,15])
6、 ndarray filter#####

Code

The function used is np.diag(ndarray, k=N), Where the value of the parameter k determines which diagonal to select the data.

Default k=0, take the main diagonal;

k =1 o&#39;clock, take the element in the upper row of the main diagonal;

k =-1 o&#39;clock, take the element in the row below the main diagonal.

python

# View the unique value in the two-dimensional array a
a =[[0,1,2],[3,4,5],[0,1,2]]print(np.unique(a))array([0,1,2,3,4,5])

# View the only row in a (that is, no duplicate rows)
print(np.unique(a,axis =0))array([[0,1,2],[3,4,5]])

# View the only column in a
print(np.unique(a,axis =1))array([[0,1,2],[3,4,5],[0,1,2]])

# View the unique value of the first row in a
print(np.unique(a[0]))array([0,1,2])

Code

X[X >10] #Filter data greater than 10 in the array X
7、 ndarray operation#####

python

np.intersect1d(x,y) #Take the intersection of x and y
np.setdiff1d(x,y)   #Take the difference of x and y, and return the elements in x but not in y
np.union1d(x,y)     #Take the union of x and y

Code

We can pass+、-、*、/Or np.add、np.substract、np.multiply 、np.divide to perform element-level addition, subtraction, multiplication, and division operations on two matrices. Because it is an element-level operation, the shapes of the two matrices must be the same or broadcastable(Broadcast)。

The so-called broadcastable here means that although the shapes of the two matrices A and B are inconsistent, A can be split into integer matrices with the same shape as B, so that when performing element-level operations, A will be performed first Split, then perform operations with B, and then combine the results together. A here is the &quot;broadcast&quot; matrix.
8、 ndarray sort#####

np.sort() and ndarray.sort() to sort the ndarray.

Code

The same is:

Both can use the parameter axis to decide which axis to sort according to, axis=Sort by column at 0, axis=Sort by row at 1;

the difference is:

np.sort()Will not change the original array; ndarray.sort()Will change the original array

Recommended Posts

Use of numpy in Python development
Use of Pandas in Python development
Subscripts of tuples in Python
Use of Anaconda in Ubuntu
Installation and use of GDAL in Python under Ubuntu
The usage of wheel in python
Summary of logarithm method in Python
Use nohup command instructions in python
Getting started with Numpy in Python
Detailed use of nmcli in CentOS8
What is the use of Python
Detailed usage of dictionary in Python
Usage of os package in python
Learning path of python crawler development
The usage of tuples in python
How to use SQLite in Python
Description of in parameterization in python mysql
Common exceptions and solutions in the use and development of Ubuntu system
The usage of Ajax in Python3 crawler
Analysis of glob in python standard library
Method of installing django module in python
What are web development frameworks in python
What is the prospect of python development
Knowledge points of shell execution in python
7 features of Python3.9
Detailed explanation of the use of pip in Python | summary of third-party library installation
Python crawler-beautifulsoup use
What is the function of adb in python
How to use the round function in python
How to use the zip function in Python
Python realizes the development of student management system
Python implements the shuffling of the cards in Doudizhu
The meaning and usage of lists in python
How to use the format function in python
How to use code running assistant in python
The consequences of uninstalling python in ubuntu, very
Introduction to the use of Hanlp in ubuntu
Example of feature extraction operation implemented in Python
Installation and use of SSH in Ubuntu environment
03. Operators in Python entry
Join function in Python
12. Network Programming in Python3
print statement in python
Detailed explanation of the implementation steps of Python interface development
python development [first article]
Use supervisor in ubuntu
How to understand the introduction of packages in Python
Basics of Python syntax
Python3 external module use
How to understand a list of numbers in python
Python|The use of operators
Concurrent requests in Python
Basic syntax of Python
Basic knowledge of Python (1)
Install python in Ubuntu
Example of how to automatically download pictures in python
Context management in Python
Prettytable module of python
Arithmetic operators in python
Write gui in python
MongoDB usage in Python