NumPy (Numerical Python) ialah perpustakaan asas untuk pengkomputeran saintifik dalam Python. Ia menambah sokongan untuk tatasusunan dan matriks berbilang dimensi yang besar, bersama-sama dengan koleksi besar fungsi matematik untuk beroperasi pada tatasusunan ini dengan cekap. NumPy digunakan secara meluas untuk analisis data, pembelajaran mesin, pembelajaran mendalam dan pengiraan berangka.
Sebelum menggunakan NumPy, perpustakaan mesti diimport ke dalam persekitaran Python anda.
import numpy as np
Tatasusunan NumPy ialah teras perpustakaan. Ia menyediakan storan yang pantas dan cekap bagi set data yang besar serta menyokong operasi bervektor.
Terdapat beberapa cara untuk mencipta tatasusunan dalam NumPy:
# 1D array arr_1d = np.array([1, 2, 3, 4]) # 2D array arr_2d = np.array([[1, 2], [3, 4], [5, 6]]) # 3D array arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
Keluaran Jangkaan:
1D array: [1 2 3 4] 2D array: [[1 2] [3 4] [5 6]] 3D array: [[[1 2] [3 4]] [[5 6] [7 8]]]
Fungsi ini mencipta tatasusunan dengan nilai yang telah ditetapkan.
# Creating arrays with initialization functions zeros_arr = np.zeros((2, 3)) ones_arr = np.ones((2, 2)) full_arr = np.full((3, 3), 7) eye_arr = np.eye(3)
Keluaran Jangkaan:
Zeros array: [[0. 0. 0.] [0. 0. 0.]] Ones array: [[1. 1.] [1. 1.]] Full array: [[7 7 7] [7 7 7] [7 7 7]] Identity matrix: [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]
NumPy menyediakan pelbagai cara untuk menjana nombor rawak.
random_arr = np.random.rand(2, 2) randint_arr = np.random.randint(1, 10, (2, 3))
Keluaran Jangkaan:
Random array: [[0.234 0.983] [0.456 0.654]] Random integer array: [[5 7 2] [3 9 1]]
arr = np.array([[1, 2, 3], [4, 5, 6]]) print("Shape:", arr.shape) print("Size:", arr.size) print("Dimensions:", arr.ndim) print("Data type:", arr.dtype) print("Item size:", arr.itemsize)
Keluaran Jangkaan:
Shape: (2, 3) Size: 6 Dimensions: 2 Data type: int32 Item size: 4
reshaped = arr.reshape(3, 2) flattened = arr.ravel() transposed = arr.transpose()
Keluaran Jangkaan:
Reshaped array: [[1 2] [3 4] [5 6]] Flattened array: [1 2 3 4 5 6] Transposed array: [[1 4] [2 5] [3 6]]
Tatasusunan NumPy menyediakan cara yang berkuasa untuk mengakses, menghiris dan mengubah suai data, membolehkan anda bekerja dengan cekap dengan tatasusunan 1D, 2D dan 3D. Dalam bahagian ini, kami akan meneroka cara mengakses elemen dan mengubah suai tatasusunan menggunakan pengindeksan dan penghirisan.
Anda boleh mengakses elemen tatasusunan menggunakan kurungan segi empat sama [ ]. Pengindeksan berfungsi untuk tatasusunan mana-mana dimensi, termasuk tatasusunan 1D, 2D dan 3D.
Anda boleh mengakses elemen individu tatasusunan 1D dengan menyatakan indeksnya.
arr = np.array([1, 2, 3, 4]) print(arr[1]) # Access second element
Keluaran Jangkaan:
2
Dalam tatasusunan 2D, anda boleh mengakses elemen dengan menentukan indeks baris dan lajur. Formatnya ialah arr[baris, lajur].
arr_2d = np.array([[1, 2, 3], [4, 5, 6]]) print(arr_2d[1, 2]) # Access element at row 1, column 2
Keluaran Jangkaan:
6
Untuk tatasusunan 3D, anda perlu menentukan tiga indeks: kedalaman, baris dan lajur. Formatnya ialah arr[kedalaman, baris, lajur].
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) print(arr_3d[1, 0, 1]) # Access element at depth 1, row 0, column 1
Keluaran Jangkaan:
6
Menghiris digunakan untuk mengekstrak subarray daripada tatasusunan yang lebih besar. Sintaks untuk menghiris ialah start:stop:step. Indeks permulaan adalah inklusif, manakala indeks berhenti adalah eksklusif.
Anda boleh menghiris tatasusunan 1D dengan menyatakan indeks mula, henti dan langkah.
arr = np.array([10, 20, 30, 40, 50]) print(arr[1:4]) # Slicing from index 1 to 3 (exclusive of index 4)
Expected Output:
[20 30 40]
In a 2D array, you can slice both rows and columns. For example, arr[start_row:end_row, start_col:end_col] will slice rows and columns.
arr_2d = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) print(arr_2d[1:3, 0:2]) # Rows from index 1 to 2, Columns from index 0 to 1
Expected Output:
[[40 50] [70 80]]
For 3D arrays, slicing works similarly by specifying the range for depth, rows, and columns.
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) print(arr_3d[1:, 0, :]) # Depth from index 1, Row 0, All columns
Expected Output:
[[5 6]]
Boolean indexing allows you to filter elements based on a condition. The condition returns a boolean array, which is then used to index the original array.
arr = np.array([10, 15, 20, 25, 30]) print(arr[arr > 20]) # Extract elements greater than 20
Expected Output:
[25 30]
You can also modify arrays by adding, removing, or altering elements using various functions.
You can append or insert elements into arrays with the following methods:
arr = np.array([1, 2, 3]) appended = np.append(arr, 4) # Add 4 at the end inserted = np.insert(arr, 1, [10, 20]) # Insert 10, 20 at index 1 concatenated = np.concatenate([arr, np.array([4, 5])]) # Concatenate arr with another array
Expected Output:
Appended: [1 2 3 4] Inserted: [ 1 10 20 2 3] Concatenated: [1 2 3 4 5]
To remove elements from an array, you can use np.delete().
arr = np.array([1, 2, 3, 4]) deleted = np.delete(arr, 1) # Remove element at index 1 slice_deleted = np.delete(arr, slice(1, 3)) # Remove elements from index 1 to 2 (exclusive of 3)
Expected Output:
Deleted: [1 3 4] Slice deleted: [1 4]
NumPy supports element-wise operations, broadcasting, and a variety of useful mathematical functions.
You can perform operations like addition, subtraction, multiplication, and division element-wise:
arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) print(arr1 + arr2) # Element-wise addition print(arr1 - arr2) # Element-wise subtraction print(arr1 * arr2) # Element-wise multiplication print(arr1 / arr2) # Element-wise division
Expected Output:
Addition: [5 7 9] Subtraction: [-3 -3 -3] Multiplication: [ 4 10 18] Division: [0.25 0.4 0.5]
These functions return a single value for an entire array.
arr = np.array([1, 2, 3, 4, 5]) print(np.sum(arr)) print(np.mean(arr)) print(np.median(arr)) print(np.std(arr)) print(np.min(arr), np.max(arr))
Expected Output:
15 3.0 3.0 1.4142135623730951 1 5
NumPy allows operations between arrays of different shapes via broadcasting, a powerful mechanism for element-wise operations.
arr = np.array([1, 2, 3]) print(arr + 10) # Broadcasting scalar value 10
Expected Output:
[11 12 13]
NumPy provides many linear algebra functions, such as:
A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) dot_product = np.dot(A, B) matrix_mult = np.matmul(A, B) inv_A = np.linalg.inv(A) det_A = np.linalg.det(A)
Expected Output:
Dot product: [[19 22] [43 50]] Matrix multiplication: [[19 22] [43 50]] Inverse of A: [[-2. 1. ] [ 1.5 -0.5]] Determinant of A: -2.0
arr = np.array([3, 1, 2]) sorted_arr = np.sort(arr)
Expected Output:
[1 2 3]
arr = np.array([1, 2, 2, 3, 3, 3]) unique_vals = np.unique(arr)
Expected Output:
[1 2 3]
arr1 = np.array([1, 2]) arr2 = np.array([3, 4]) vstacked = np.vstack((arr1, arr2)) hstacked = np.hstack((arr1, arr2)) splits = np.split(np.array([1, 2, 3, 4]), 2)
Expected Output:
Vertical stack: [[1 2] [3 4]] Horizontal stack: [1 2 3 4] Splits: [array([1, 2]), array([3, 4])]
NumPy is an essential library for any Python user working with large amounts of numerical data. With its efficient handling of arrays and vast range of mathematical operations, it lays the foundation for more advanced topics such as machine learning, data analysis, and scientific computing.
Atas ialah kandungan terperinci Lembaran Penipuan Numpy. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!