An article to learn numpy

An article to learn numpy

Introduction

This article explains how to use numpy.

Introduction

NumPy is an open source library for scientific computing in the Python language. This library provides many functions, especially for array manipulation and linear algebra operations.

Let's introduce some of the main functions of NumPy:

1. Ndarray data type

ndarrayIs a data type in the NumPy module, which is a multidimensional array (that is, an N-dimensional array) composed of a collection of elements of the same type. And this data type has many special properties and methods, such as shape, dtype, reshape(), and mean()so on.

2. Array operations

The NumPy library provides many operations on arrays, including creating arrays, copying, and sorting.

  • Create arrays: use numpy.array()functions.
  • Replication: copy()How to use.
  • Sorting: using sort()method.

3. Array indexing, slicing and iteration

Like ordinary python lists, indexing, slicing, and iteration can also be used in NumPy, and the advantage is that array processing operations can be performed efficiently. The difference between the array index method and the ordinary list is that multiple integers can be passed in as indexes through commas to select a single element.

4. Array shape operations

This means changing the shape of the array, such as changing the number of rows and columns or reshaping the array. Its size can be changed using reshape()functions.

5. Matrix operations

The NumPy library is widely implemented for a unified format such as a linear algebraic matrix. It provides a large number of functions and methods for processing matrices and other mathematical structures, and is often used in machine learning, image and signal processing and other fields.

6. Array operation

NumPy has many built-in basic mathematical functions, which can be called as methods of arrays, and basic mathematical operations such as addition, subtraction, multiplication, division, and remainder/modulo operations can be performed element-by-element, making it easier to use data for mathematical calculations. Includes functions such as sum, average, standard deviation, maximum, minimum, and more.

7. Reading and writing files

NumPy also supports reading and writing various types of files and text files, and loading and processing data from them. When you want to read data quickly, such functions can quickly convert it into an array format.

In summary, NumPy provides a powerful set of data objects that allow you to use entire arrays to perform mathematical operations or manipulate sequence data.

code example

Ok, so here I give you some sample code for NumPy syntax:

1. Create an array

Notes:

  • Import the NumPy library and name it np.
  • np.array()Create a one-dimensional array from a function.
  • Use print()a function to output this one-dimensional array.

code:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)

operation result:

[1 2 3 4 5]

explain:

This code defines a one-dimensional array arrthat contains the numbers 1 through 5. print()function is used to output this array. Since the array contains elements of integer type, when print()the function is called, the elements are separated by spaces, and the array itself is displayed within square brackets.

2. Copy the array

Notes:

  • Import the NumPy library and name it np.
  • np.array()Create a one-dimensional array from a function.
  • Use .copy()method to create a copy of the original array.
  • Use print()a function to output an array of copies.

code:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
copy_arr = arr.copy()
print(copy_arr)

operation result:

[1 2 3 4 5]

explain:

Similar to the first example, this code snippet also creates a one-dimensional array containing the numbers 1 to 5. Then, use .copy()the method to create a copy array called copy_arr, and use print()the function to output the copy array. Since copy_arr is a copy of arr, it is exactly the same as the original array.

3. Sorting an array

Notes:

  • Import the NumPy library and name it np.
  • np.array()Create a one-dimensional array from a function.
  • Use np.sort()a function to sort the array.
  • Use print()a function to output the sorted array.

code:

import numpy as np

arr = np.array([3, 2, 0, 1, 4])
sorted_arr = np.sort(arr)
print(sorted_arr)

operation result:

[0 1 2 3 4]

explain:

This example creates a one-dimensional array containing the integers 0, 1, 2, 3, 4. Then, use a function np.sort()to sort the array. Finally, use print()a function to output the new sorted array. In this example, calling np.sort() returns a new sorted array, leaving the original array unchanged. As you can see, the new array is sorted in ascending order.

4. Array indexing, slicing, and iteration

Notes:

  • Import the NumPy library and name it np.
  • np.array()Create a one-dimensional array from a function.
  • Output the first element using indexing.
  • Use slices to output the 2nd to 4th elements (excluding the 5th element).
  • Use the interval parameter to output even-numbered elements.
  • Using a for loop, iterates through the array and outputs each element.

code:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr[0])     # 输出第一个元素
print(arr[1:3])   # 输出2到4之间的元素(不包括4)
print(arr[::2])   # 输出偶数位置的元素
for i in arr:
    print(i)      # 循环遍历输出所有元素

operation result:

1
[2 3]
[1 3 5]
1
2
3
4
5

explain:

This example demonstrates how to use indexing, slicing and iteration of NumPy arrays. First, output the first element in the array using the indexing syntax. Next, use slice syntax to output elements between 2 and 4. Then, use the interval parameter to output even-numbered elements. Finally, use the iterator to traverse the entire array under the for loop and output each element.

5. Array shape operations

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
reshape_arr = arr.reshape(2, 3)
print(reshape_arr)

output:

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

Calling .reshape()methods can change the shape of the array. The above example converts the original array into a two-dimensional array with two rows and three columns.

6. Matrix operations

Notes:

  • Import the NumPy library and name it np.
  • Use np.array()the function to create two two-dimensional arrays A and B, respectively, to represent the operands of matrix multiplication.
  • Compute the matrix product using np.dot()a function and save the result in a new array called C.
  • Transpose A using the .T property and save the result in a new array called D.
  • Use print()the function to output the values ​​of arrays C and D in sequence.

code:

import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])

C = np.dot(A, B)  # 矩阵的乘法
D = A.T           # 转置

print(C)
print(D)

operation result:

[[19 22]
 [43 50]]
[[1 3]
 [2 4]]

explain:

This example demonstrates how to use NumPy for matrix manipulation. First, define two matrices A and B, then use np.dot()the function to calculate their matrix product and store the result in an array called C. .TNext, transpose the original matrix A using attributes and store the result in an array called D. Finally, use print()the function to print out the values ​​of arrays C and D. Note that each element in matrix C is calculated by multiplying and adding the corresponding elements of matrices A and B, while array D is the transpose of the original matrix A.

7. Array operation

Notes:

  • Import the NumPy library and name it np.
  • np.array()Create a one-dimensional array from a function.
  • Use .reshape()the method to transform the array into a two-dimensional array and save it into a new array called reshape_arr.
  • Use print()a function to output a new array.

code:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
reshape_arr = arr.reshape(2, 3)
print(reshape_arr)

operation result:

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

explain:

This example demonstrates how to use .reshape()methods to reshape an original one-dimensional array into a two-dimensional array. In this example, reshape()the method will be used to initialize the original array into a two-row, three-column array. So the function returns a Reshaped array where the first row contains the numbers [1, 2, 3] and the second row contains the numbers [4, 5, 6]. Finally, use print()the statement to print the value of the Reshaped array on the console.

8. Reading and writing files

Notes:

  • Import the NumPy library and name it np.
  • np.array()Create a two-dimensional array from a function.
  • Use np.save()a function to store the array to a file, specifying the name of the saved file.
  • Use np.load()the function to load the array from the file and store it in a new array variable named new_arr.
  • Use print()the function to output a new two-dimensional array.

code:

import numpy as np

arr = np.array([[1, 2], [3, 4]])
np.save("array_file", arr)  # 将数组保存到文件中

new_arr = np.load("array_file.npy")  # 从文件中加载数组
print(new_arr)

operation result:

[[1 2]
 [3 4]]

explain:

This example demonstrates how to store a Numpy array to disk, then load the saved array again from a file, and print it as output. First, a two-dimensional array containing the numbers 1 to 4 is defined. Then, use np.save()a function to store the array into a file called "array_file.npy". Next, use np.load()functions to read binary data from this file and store it in a new array new_arr. Finally, use print()the statement to output the contents of this new array to demonstrate that the data was successfully read from the file and reloaded into memory.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130793105