python Extension Library numpy Getting Started Tutorial

  • 2021-12-12 05:11:38
  • OfStack

Directory 1. What is numpy? 2. numpy Array 2.1 Array Use 2.2 Create Array 1. Use empty Create Null Array 2. Use arange Function Create 3. Use zeros Function Generate Array 4. ones Function Generate Array 5. diag Function Generate Diagonal Matrix 6. N Dimensional Array 2.3 Access Array Elements 3. Understanding Matrix 3.1 Broadcast

1. What is numpy?

Extension library numpy is an important extension library of Python to support scientific computing. It is one of the necessary extension libraries in the field of data analysis and scientific computing, such as scipy, pandas, sklearn, etc. It provides powerful N dimensional array and its related operations, complex broadcast functions, C/C + + and Fortran code integration tools, linear algebra, Fourier transform and random number generation functions, etc. This chapter introduces arrays and matrices and their related operations, which lays a good foundation for learning and understanding data analysis and machine learning in later chapters.

Simply put, it is something you use to lay the foundation for the field of artificial intelligence. The private words are good, the foundation is not firm, and the earth shakes ~

So this place should study hard ~ ~

2. numpy Array

The data type used in numpy is not the data type that comes with python list , but in numpy ndarray

Then why use it ndarray Instead of using list What about?

Because ndarray is written by c/c + +, it takes less memory and is faster to use

There are many ways to create an ndarray, and here we say that we use array method to transform it


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author :  Smly
# @datetime :  2021/9/26 22:22 
# @Version :  1.0

import numpy as np

li = [1, 2, 3]
tp = (1, 2, 3)

nday1 = np.array(li)
nday2 = np.array(tp)

print("***** Type *****")
print(type(nday1))
print(type(nday2))

print("***** Array *****")
print(nday1)
print(nday2)

Output:


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]

2.1 Array usage

If the elements are the same, you can add, subtract, multiply and divide

If the number of elements is the same, you can add and subtract between arrays

If the number of elements is the same, you can multiply and divide between arrays

Multiplication and division of a number can be automatically carried out to all elements

Look at examples to understand:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author :  Smly
# @datetime :  2021/9/26 22:22 
# @Version :  1.0
import numpy as np	
li = [1, 2, 3]	#  List 
tp = (1, 2, 3)	#  Tuple 
nday1 = np.array(li)	#  Built-in method converts the list to ndarray
nday2 = np.array(tp)	#  Built-in method converts tuples to ndarray
nday3 = np.array(range(5)) #  Use range Built-in function method generation ndarray Continuous array 
nday4 = np.array(range(5, 10))  #  Use range Built-in function method generation ndarray Continuous array 
print("***** Type *****")
print(type(nday1))
print(type(nday2))
print(type(nday3))
print(type(nday4))
print("***** Array *****")
print(nday1)
print(nday2)
print(nday3)
print(nday4)
print("***** Array addition and subtraction *****")
print(nday2 + nday1)
print(nday2 - nday1)
print(nday4 - nday3)
print(nday3 + nday4)
#  If the number of elements is the same, you can add and subtract between arrays 
print("***** Array multiplication and division *****")
print(nday2 * nday1)
print(nday2 // nday1)
print(nday4 * nday3)
print(nday4 // nday3)
#  If the number of elements is the same, you can multiply and divide between arrays 
print(nday1 * 3)
print(nday2 // 2)
print(nday3 * 2)
print(nday4 // 2)
#  Multiplication and division of a number can be automatically carried out to all elements 


Run results:


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
[0 1 2 3 4]
[5 6 7 8 9]
***** Array addition and subtraction *****
[2 4 6]
[0 0 0]
[5 5 5 5 5]
[ 5  7  9 11 13]
***** Array multiplication and division *****
[1 4 9]
[1 1 1]
[ 0  6 14 24 36]
[0 0 0 0 0]
[3 6 9]
[0 1 1]
[0 2 4 6 8]
[2 3 3 4 4]

2.2 Create an Array

Just array() The method is to convert iterative objects such as lists and tuples into ndarray arrays

The next thing to say is to automatically create arrays

1. Create an empty array using empty

There will be an initial value in it, but the array will initially be None


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author :  Smly
# @datetime :  2021/9/28 12:29 
# @Version :  1.0
import numpy as np
em1 = np.empty(5)       #  Create 1 The length is 5 Empty array of 
em2 = np.empty((2, 2))  #  Create 1 A 2*2 Empty of 2 Dimensional array 

print("1 An array of dimensions with a length of 5", em1)
print("2 An array of dimensions with a length of 2*2", em2)

Output:


[9.96754604e-312 9.96754614e-312 2.60799828e-310 9.34609789e-307
 0.00000000e+000]
[[6.95299778e-310 9.96747617e-312]
 [0.00000000e+000 6.95299776e-310]]

2. Use the arange function to create

arange is a method that comes with numpy. The function of range is almost the same as the built-in function of Python, which is to generate arrays

Import the numpy package first


import numpy as np

Then create an array


print("*****ararge Create an array *****")

aran_arr1 = np.arange(5)
aran_arr2 = np.arange(5, 10)

print("***** Type *****")
print(type(aran_arr1))
print(type(aran_arr2))

print("***** Array *****")
print(aran_arr1)
print(aran_arr2)

3. Use the zeros function to generate an array

The zeros function is a method that comes with numpy. The function is to generate a specified number of all 01-dimensional arrays, all 02-dimensional arrays, and so on

Look at the following example:

Generate a 1-dimensional array with 3 elements and a 1-dimensional array with 5 elements:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author :  Smly
# @datetime :  2021/9/27 21:31 
# @Version :  1.0

import numpy as np
zero_arr = np.zeros(3)
zrro_arr2 = np.zeros(5)
print(zero_arr)
print(zrro_arr2)

Run results:

[0. 0. 0.]
[0. 0. 0. 0. 0.]

Of course, this is only a 1-digit array, and you can also generate 2-dimensional arrays, that is, matrices

Use the following code to generate a matrix with 3 rows and 3 columns


zero_arr3 = np.zeros((3, 3))

Output to see:


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
0

Run results:

[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

4. The ones function generates an array

Use ones function to generate all 1 function in the same way as zeros


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
1

Output:

[1. 1. 1.]

Generate a matrix with 3 rows and 3 columns


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
2

Output:

[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]

5. Diagonal Matrix Generated by diag Function

What is a diagonal matrix? You should have heard of diagonals, and a matrix is a matrix generated on diagonals

Function argument is 1 yuan ancestor

Look at the code and the running results can understand more deeply


import numpy as np

diag_arr = np.diag((4, 3, 2, 1))

The output of diag_arr is:

[[4 0 0 0]
[0 3 0 0]
[0 0 2 0]
[0 0 0 1]]

See if the diagonal is an argument to your function

6. N Dimensional Array

N Dimensional Array is a multi-dimensional array, which can be understood as an array inside or an array inside. You can refer to this form

[[[1 2]
[3 4]]
[[5 6]
[7 8]]]

This concept is really a bit abstract and difficult to understand. This is a 3-D array that is converted from a 3-D list using the array method to ndarray

Code:


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
4

Of course, 2-dimensional arrays are also N-dimensional arrays

2.3 Access to Array Elements

numpy comes with one insert Function, you can insert elements into an array

Look at examples:


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
5

Output:

[1 1 2 3 4 2 3 4 5 6 7 8 2 4 6 8]

There is also a self-contained add function, which can add and subtract arrays

For arrays, you can use subscripts to get array elements


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
6

The output is:

2

Of course, it is an array, and you can also use loop statements to traverse the array.

STEP 3 Understand the Matrix

Arrays are arrays and matrices are matrices.

Array is a kind of data structure, which can store a variety of data and can have multiple dimensions

Matrix is a concept in mathematics, which can only store numbers and can only be in two-dimensional form

The method of generating matrix is the same as the method of generating N dimension array

First use lists to create a 2-D list, and then use numpy to transform it into a matrix. Of course, there are several ways to generate a matrix


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
7

Output the matrix:


 Output Matrix:  [[1 2 3 4]
 [5 6 7 8]]
 Matrix in Python Type of:  <class 'numpy.matrix'>
 In numpy Type in:  int32

Matrix can perform a variety of mathematical operations, in numpy have been well supported, here will not elaborate

3.1 Broadcast

What is broadcast, broadcast is to be able to send your things to each area, 1 in the computer is to send information to each computer in the local area network.

And in numpy there is also a broadcast, but it automatically adds elements to arrays and matrices. As you can see above, if an array is multiplied by one element, all elements in the array will be multiplied by this number


***** Type *****
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
***** Array *****
[1 2 3]
[1 2 3]
9

Output:

[10 20 30 40]

This is broadcast, which is to broadcast the number 10 into the array converted by li, which can multiply all elements of the array by 10.

And arrays of different dimensions can do the same


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author :  Smly
# @datetime :  2021/9/27 13:40 
# @Version :  1.0
import numpy as np
li = [[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]]
gb1 = np.array(li)
li1 = [1, 2, 3, 4]
gb2 = np.array(li1)
print(gb1*gb2)

Broadcast each element of a 1-dimensional array to a 2-dimensional array one by one, provided that:

The number of 1-D arrays in 2-D arrays is the same as the number of 1-D arrays

Run results:

[[ 1 4 9 16]
[ 5 12 21 32]
[ 2 8 18 32]]

The above is the python Extension Library numpy Getting Started tutorial details, more about numpy Library Getting Started information please pay attention to other related articles on this site!


Related articles: