Preface
NumPy
It is a very important library in the Python scientific computing library, mainly used to deal with large multidimensional arrays and matrix operations. It provides a large number of mathematical functions to manipulate these arrays.NumPy
The core ofndarray
Object, this object is a multi-dimensional array that can store data of the same type.
Below isNumPy
Detailed usage and function introduction:
1. Import NumPy
In useNumPy
Before, we need to import the library first, usually we willNumPy
bynp
As an alias:
import numpy as np
2. Create an array
The array in NumPy is calledndarray
, there are many ways to create arrays:
a) Create an array using array()
# Create an array from a Python listarr = ([1, 2, 3, 4]) print(arr) # Output: [1 2 3 4] # Create a multi-dimensional arrayarr_2d = ([[1, 2], [3, 4]]) print(arr_2d) # Output: [[1 2] [3 4]]
b) Create a specific array of values using zeros(), ones() and full()
# Create an array with all 0szeros_arr = ((2, 3)) print(zeros_arr) # Output: [[0. 0. 0.] [0. 0. 0.]] # Create an array with all 1sones_arr = ((2, 3)) print(ones_arr) # Output: [[1. 1. 1.] [1. 1. 1.]] # Create an array of specified valuesfull_arr = ((2, 2), 5) print(full_arr) # Output: [[5 5] [5 5]]
c) Create a sequence array using arange() and linspace()
# Create an arithmetic arrayarr_range = (0, 10, 2) print(arr_range) # Output: [0 2 4 6 8] # Create a linear interval arrayarr_linspace = (0, 1, 5) print(arr_linspace) # Output: [0. 0.25 0.5 0.75 1. ]
3. Array properties
ndarray
Objects have multiple attributes that can obtain information about arrays:
arr = ([[1, 2, 3], [4, 5, 6]]) print() # The shape of the array (2, 3)print() # Number of elements in the array 6print() # Dimension 2 of the arrayprint() # Data type of array element int64
4. Array indexing and slicing
NumPy
Arrays support multi-dimensional indexing and slicing operations.
a) One-dimensional array index
arr = ([1, 2, 3, 4, 5]) print(arr[0]) # Output the first element: 1print(arr[-1]) # Output the last element: 5
b) Multidimensional array index
arr_2d = ([[1, 2, 3], [4, 5, 6]]) print(arr_2d[0, 2]) # Output elements of the first row and third column: 3print(arr_2d[1, -1]) # Output the last element on the second line: 6
c) Slice
# 1D array slicearr = ([1, 2, 3, 4, 5]) print(arr[1:4]) # Output: [2 3 4] # Multidimensional array slicearr_2d = ([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(arr_2d[0:2, 1:3]) # Output: [[2 3] [5 6]]
5. Mathematical operations
NumPy
The array can be operated under the broadcast mechanism.
a) Basic operation of arrays
arr = ([1, 2, 3]) print(arr + 2) # Output: [3 4 5]print(arr * 3) # Output: [3 6 9]print(arr ** 2) # Output: [1 4 9]
b) Operations between arrays
arr1 = ([1, 2, 3]) arr2 = ([4, 5, 6]) print(arr1 + arr2) # Output: [5 7 9]print(arr1 * arr2) # Output: [4 10 18]
c) Universal functions (Universal Functions)
NumPy
Provides many general mathematical functions that can be applied to each element of an array, e.g.sin()
、exp()
、sqrt()
wait.
arr = ([1, 2, 3]) print((arr)) # Output: Sine value of each element of the arrayprint((arr)) # Output: Exponential value of each element of the arrayprint((arr)) # Output: Square root of each element of the array
6. Array shape operation
NumPy
Many tools are provided to change the shape of an array.
a) reshape()
Change the array shape
arr = ([[1, 2, 3], [4, 5, 6]]) reshaped_arr = ((3, 2)) print(reshaped_arr) #Output:# [[1 2] # [3 4] # [5 6]]
b) Array transposition
arr = ([[1, 2, 3], [4, 5, 6]]) print() #Output:# [[1 4] # [2 5] # [3 6]]
7. Merge and split arrays
NumPy
Supports merging and segmenting operations of arrays.
a) Merge of arrays
arr1 = ([[1, 2], [3, 4]]) arr2 = ([[5, 6]]) # Vertical mergevstack_arr = ((arr1, arr2)) print(vstack_arr) # Output: [[1 2] [3 4] [5 6]] # Horizontal mergerhstack_arr = ((arr1, )) print(hstack_arr) # Output: [[1 2 5] [3 4 6]]
b) Splitting of arrays
arr = ([[1, 2, 3], [4, 5, 6]]) # Vertical segmentationvsplit_arr = (arr, 2) print(vsplit_arr) # Output two 2x3 arrays # Horizontal segmentationhsplit_arr = (arr, 3) print(hsplit_arr) # Output three 2x1 arrays
8. Boolean index and conditional filtering
NumPy supports Boolean conditional filtering and indexing operations.
arr = ([1, 2, 3, 4, 5]) print(arr[arr > 3]) # Output: [4 5] # Conditional assignmentarr[arr > 3] = 0 print(arr) # Output: [1 2 3 0 0]
9. Commonly used statistical functions
NumPy
Provides rich statistical functions to facilitate statistical calculation of arrays.
arr = ([1, 2, 3, 4, 5]) print((arr)) # Average: 3.0print((arr)) # Sum: 15print((arr)) # Standard deviation: 1.414print((arr)) # Minimum value: 1print((arr)) # Maximum value: 5
10. Random number generation
NumPy
ofrandom
The module provides the function of generating random numbers.
# Generate a random floating point number between [0, 1)print(()) # Generate a random number that obeys the standard normal distributionprint(()) # Generate a random integer in the specified rangeprint((0, 10, (3, 3))) # Output a 3x3 random integer matrix
11. Broadcasting mechanism
NumPy
has a broadcasting mechanism, which means that when the two arrays of operations have different shapes, but the shape of one of the arrays can match the shape of the other array by repeating elements in certain dimensions, NumPy will automatically expand the element and perform operations.
# Add a 1x3 array and a 3x1 arraya = ([1, 2, 3]) b = ([[1], [2], [3]]) # Broadcasting mechanism: broadcast b to [1, 2, 3], and then perform additionresult = a + b print(result) #Output:# [[2 3 4] # [3 4 5] # [4 5 6]]
12. Matrix operation of arrays
The matrix operation functions in NumPy include common linear algebraic operations such as matrix multiplication, matrix transposition, and inversion. Especially suitable for linear algebraic methods used in scientific computing and machine learning.
a) Matrix multiplication
The @ symbol or () function can be used for matrix multiplication.
# Define two matricesA = ([[1, 2], [3, 4]]) B = ([[5, 6], [7, 8]]) #Matrix MultiplicationC = A @ B print(C) #Output:# [[19 22] # [43 50]] # Use dot functionD = (A, B) print(D) # The output is the same as above
b) Matrix Transposition
#Matrix TranspositionA_T = print(A_T) #Output:# [[1 3] # [2 4]]
d) Calculate the determinant
Use () to calculate the determinant of the matrix.
A = ([[1, 2], [3, 4]]) det_A = (A) print(det_A) # Output: -2.0
e) Eigenvalues and eigenvectors
Use () to calculate the eigenvalues and eigenvectors of the matrix.
A = ([[1, 2], [3, 4]]) eigenvalues, eigenvectors = (A) print("Eigenvalue:", eigenvalues) print("Eigenvector:", eigenvectors) #Output:# Eigenvalue: [-0.37228132 5.37228132]# Eigenvector:# [[-0.82456484 -0.41597356] # [ 0.56576746 -0.90937671]]
12. Array sorting and conditional filtering
a) Sort
Use the () function to sort the array. This function returns a sorted array without modifying the original array.
a = ([3, 1, 2, 4]) sorted_a = (a) print(sorted_a) # Output: [1 2 3 4]
b) Conditional filtering
NumPy provides flexible conditional filtering operations, and can use a boolean array to select elements that meet the conditions.
# Create an arraya = ([1, 2, 3, 4, 5]) # Filter out elements greater than 2filtered_a = a[a > 2] print(filtered_a) # Output: [3 4 5] # Use where conditions to filterb = (a > 2, a, -1) # If greater than 2, keep the original value, otherwise set to -1print(b) # Output:[-1 -1 3 4 5]
Summarize
This is all about this article about the usage of numpy in python. For more related content on the usage of numpy in python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!