」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Numpy 備忘單

Numpy 備忘單

發佈於2024-11-17
瀏覽:957

Numpy Cheat Sheet

Comprehensive Guide to NumPy: The Ultimate Cheat Sheet

NumPy (Numerical Python) is a fundamental library for scientific computing in Python. It adds support for large multi-dimensional arrays and matrices, along with a vast collection of mathematical functions to operate on these arrays efficiently. NumPy is widely used for data analysis, machine learning, deep learning, and numerical computation.


1. Importing NumPy

Before using NumPy, the library must be imported into your Python environment.


import numpy as np



2. NumPy Arrays

NumPy arrays are the core of the library. They provide fast and efficient storage of large datasets and support vectorized operations.

Creating Arrays

There are several ways to create arrays in NumPy:

1D, 2D, and 3D Array Creation


# 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]]])


Expected Output:


1D array: [1 2 3 4]
2D array: [[1 2]
           [3 4]
           [5 6]]
3D array: [[[1 2]
            [3 4]]
           [[5 6]
            [7 8]]]



3. Array Initialization Functions

Zeros, Ones, Full, Empty, Eye, Identity

These functions create arrays with predefined values.

  • np.zeros(shape) – Returns a new array of given shape filled with zeros.
  • np.ones(shape) – Returns a new array filled with ones.
  • np.full(shape, fill_value) – Returns a new array of the given shape, filled with a specified value.
  • np.empty(shape) – Returns an uninitialized array of the specified shape.
  • np.eye(N) – Returns a 2D identity matrix with 1s on the diagonal.
  • np.identity(N) – Creates a square identity matrix of size N.

# 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)


Expected Output:


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.]]



4. Random Array Generation

NumPy provides various ways to generate random numbers.

Random Numbers with np.random

  • np.random.rand(shape) – Generates random values in a given shape (between 0 and 1).
  • np.random.randint(low, high, size) – Returns random integers from low (inclusive) to high (exclusive).
  • np.random.choice(array) – Randomly selects an element from an array.

random_arr = np.random.rand(2, 2)
randint_arr = np.random.randint(1, 10, (2, 3))


Expected Output:


Random array: [[0.234 0.983]
               [0.456 0.654]]
Random integer array: [[5 7 2]
                       [3 9 1]]



5. Inspecting and Manipulating Arrays

Array Attributes

  • ndarray.shape – Returns the dimensions of the array.
  • ndarray.size – Returns the number of elements in the array.
  • ndarray.ndim – Returns the number of dimensions.
  • ndarray.dtype – Returns the type of elements in the array.
  • ndarray.itemsize – Returns the size of each element in the array (in bytes).

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)


Expected Output:


Shape: (2, 3)
Size: 6
Dimensions: 2
Data type: int32
Item size: 4


Array Reshaping

  • reshape(shape) – Reshapes the array to a specified shape without changing its data.
  • ravel() – Returns a flattened version of the array (1D).
  • transpose() – Transposes the array.

reshaped = arr.reshape(3, 2)
flattened = arr.ravel()
transposed = arr.transpose()


Expected Output:


Reshaped array: [[1 2]
                 [3 4]
                 [5 6]]
Flattened array: [1 2 3 4 5 6]
Transposed array: [[1 4]
                   [2 5]
                   [3 6]]



6. Array Indexing, Slicing, and Modifying Elements

NumPy arrays provide powerful ways to access, slice, and modify data, enabling you to efficiently work with 1D, 2D, and 3D arrays. In this section, we will explore how to access elements and modify arrays using indexing and slicing.

Basic Indexing

You can access elements of an array using square brackets [ ]. Indexing works for arrays of any dimensionality, including 1D, 2D, and 3D arrays.

1D Array Indexing

You can access individual elements of a 1D array by specifying their index.


arr = np.array([1, 2, 3, 4])
print(arr[1])  # Access second element


Expected Output:


2


2D Array Indexing

In a 2D array, you can access elements by specifying the row and column indices. The format is arr[row, column].


arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d[1, 2])  # Access element at row 1, column 2


Expected Output:


6


3D Array Indexing

For 3D arrays, you need to specify three indices: depth, row, and column. The format is arr[depth, row, column].


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


Expected Output:


6



Slicing

Slicing is used to extract subarrays from larger arrays. The syntax for slicing is start:stop:step. The start index is inclusive, while the stop index is exclusive.

1D Array Slicing

You can slice a 1D array by specifying the start, stop, and step indices.


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]


2D Array Slicing

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]]


3D Array Slicing

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

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]



Adding, Removing, and Modifying Elements

You can also modify arrays by adding, removing, or altering elements using various functions.

Adding Elements

You can append or insert elements into arrays with the following methods:

  • np.append(arr, values) – Appends values to the end of an array.
  • np.insert(arr, index, values) – Inserts values at a specified index.
  • np.concatenate([arr1, arr2]) – Concatenates two arrays along an existing axis.

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]


Removing Elements

To remove elements from an array, you can use np.delete().

  • np.delete(arr, index) – Deletes the element at the specified index.
  • np.delete(arr, slice) – Deletes elements in a slice of the array.

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]



7. Mathematical Operations

NumPy supports element-wise operations, broadcasting, and a variety of useful mathematical functions.

Basic Arithmetic

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]


Aggregation Functions

These functions return a single value for an entire array.

  • np.sum(arr) – Returns the sum of array elements.
  • np.mean(arr) – Returns the mean of array elements.
  • np.median(arr) – Returns the median of array elements.
  • np.std(arr) – Returns the standard deviation.
  • np.var(arr) – Returns the variance.
  • np.min(arr) / np.max(arr) – Returns the minimum/maximum element.

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



8. Broadcasting and Vectorization

NumPy allows operations between arrays of different shapes via broadcasting, a powerful mechanism for element-wise operations.

Example: Broadcasting


arr = np.array([1, 2, 3])
print(arr   10)  # Broadcasting scalar value 10


Expected Output:


[11 12 13]



9. Linear Algebra in NumPy

NumPy provides many linear algebra functions, such as:

  • np.dot() – Dot product of two arrays.
  • np.matmul() – Matrix multiplication.
  • np.linalg.inv() – Inverse of a matrix.
  • np.linalg.det() – Determinant of a matrix.
  • np.linalg.eig() – Eigenvalues and eigenvectors.

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



10. Other Useful Functions

Sorting

  • np.sort(arr) – Returns a sorted array.

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


Expected Output:


[1 2 3]


Unique Values

  • np.unique(arr) – Returns the sorted unique elements of an array.

arr = np.array([1, 2, 2, 3, 3, 3])
unique_vals = np.unique(arr)


Expected Output:


[1 2 3]


Stacking and Splitting

  • np.vstack() – Stacks arrays vertically.
  • np.hstack() – Stacks arrays horizontally.
  • np.split() – Splits arrays into multiple sub-arrays.

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])]



Conclusion

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.

版本聲明 本文轉載於:https://dev.to/harshm03/numpy-cheat-sheet-5cjj?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-17
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-17
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-17
  • Numpy 備忘單
    Numpy 備忘單
    Comprehensive Guide to NumPy: The Ultimate Cheat Sheet NumPy (Numerical Python) is a fundamental library for scientific computing in Python. ...
    程式設計 發佈於2024-11-17
  • 你需要像專業人士一樣閱讀科技文章
    你需要像專業人士一樣閱讀科技文章
    在快节奏的技术世界中,并非您阅读的所有内容都是准确或公正的。并非您读到的所有内容都是由人类编写的! 细节可能存在微妙的错误,或者文章可能故意误导。让我们来看看一些可以帮助您阅读科技文章或任何媒体内容的技能。 1. 培养健康的怀疑态度 培养健康的怀疑态度至关重要。质疑大胆的主张,寻找...
    程式設計 發佈於2024-11-17
  • 如何找到一個多維數組中存在但另一個多維數組中不存在的行?
    如何找到一個多維數組中存在但另一個多維數組中不存在的行?
    比較多維數組的關聯行您有兩個多維數組,$pageids 和$parentpage,其中每行代表一個包含列的記錄“id”、“連結標籤”和“url”。您想要尋找 $pageids 中存在但不在 $parentpage 中的行,從而有效地建立一個包含缺少行的陣列 ($pageWithNoChildren)...
    程式設計 發佈於2024-11-17
  • 為什麼 Windows 中會出現「Java 無法辨識」錯誤以及如何修復它?
    為什麼 Windows 中會出現「Java 無法辨識」錯誤以及如何修復它?
    解決Windows 中的「Java 無法識別」錯誤嘗試在Windows 7 上檢查Java 版本時,使用者可能會遇到錯誤「'Java' 無法識別”作為內部或外部命令。 」此問題通常是由於缺少Java 安裝或環境變數不正確而引起的。要解決此問題,您需要驗證Java 安裝並配置必要的環境...
    程式設計 發佈於2024-11-17
  • 儘管檔案存在且有權限,為什麼 File.delete() 會回傳 False?
    儘管檔案存在且有權限,為什麼 File.delete() 會回傳 False?
    儘管存在並進行權限檢查,File.delete() 返回False使用FileOutputStream 寫入檔案後嘗試刪除檔案時,某些使用者遇到意外問題: file.delete() 傳回false。儘管檔案存在且所有權限檢查(.exists()、.canRead()、.canWrite()、.ca...
    程式設計 發佈於2024-11-17
  • 如何有效地從 Go 中的切片中刪除重複的對等點?
    如何有效地從 Go 中的切片中刪除重複的對等點?
    從切片中刪除重複項給定一個文字文件,其中包含表示為具有“Address”和“PeerID”的對象的對等點清單屬性,任務是根據程式碼配置中「Bootstrap」切片中匹配的「Address」和「PeerID」刪除所有重複的對等點。 為了實現此目的,我們迭代切片中的每個對等點物件多次。在每次迭代期間,我...
    程式設計 發佈於2024-11-17
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1和$array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建構一...
    程式設計 發佈於2024-11-17
  • 如何自訂Bootstrap 4的檔案輸入元件?
    如何自訂Bootstrap 4的檔案輸入元件?
    繞過 Bootstrap 4 檔案輸入的限制Bootstrap 4 提供了自訂檔案輸入元件來簡化使用者的檔案選擇。但是,如果您希望自訂「選擇檔案...」佔位符文字或顯示所選檔案的名稱,您可能會遇到一些挑戰。 更改 Bootstrap 4.1 及更高版本中的佔位符自 Bootstrap 4.1 起,佔...
    程式設計 發佈於2024-11-17
  • 如何在 CSS 盒子上創建斜角?
    如何在 CSS 盒子上創建斜角?
    在 CSS 框上建立斜角可以使用多種方法在 CSS 框上實現斜角。一種方法描述如下:使用邊框的方法此技術依賴於沿容器左側建立透明邊框和沿底部建立傾斜邊框。以下程式碼示範如何實現:<div class="cornered"></div> <div cl...
    程式設計 發佈於2024-11-17
  • 如何在 Pandas DataFrame 中的字串中新增前導零?
    如何在 Pandas DataFrame 中的字串中新增前導零?
    在 Pandas Dataframe 中的字串中加入前導零在 Pandas 中,處理字串有時需要修改其格式。一項常見任務是向資料幀中的字串新增前導零。這在處理需要轉換為字串格式的數值資料(例如 ID 或日期)時特別有用。 要實現此目的,您可以利用 Pandas Series 的 str 屬性。此屬性...
    程式設計 發佈於2024-11-17
  • 您是否應該異步加載腳本以提高網站效能?
    您是否應該異步加載腳本以提高網站效能?
    非同步腳本載入以提高網站效能在現今的Web 開發領域,優化頁面載入速度對於使用者體驗和搜尋引擎優化至關重要。提高效能的有效技術之一是非同步載入腳本,使瀏覽器能夠與其他頁面元素並行下載腳本。 傳統方法是將腳本標籤直接放置在 HTML 文件中,但這種方法常常會造成瓶頸因為瀏覽器必須等待每個腳本完成載入才...
    程式設計 發佈於2024-11-17
  • 如何將 Python 日期時間物件轉換為自紀元以來的毫秒數?
    如何將 Python 日期時間物件轉換為自紀元以來的毫秒數?
    在Python 中將日期時間物件轉換為自紀元以來的毫秒數Python 的datetime 物件提供了一種穩健的方式來表示日期和時間。但是,某些情況可能需要將 datetime 物件轉換為自 UNIX 紀元以來的毫秒數,表示自 1970 年 1 月 1 日協調世界時 (UTC) 午夜以來經過的毫秒數。...
    程式設計 發佈於2024-11-17

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3