一、ndarray數據類型
numpy最核心的數據類型是ndarray,它是N維數組對象,代表著相同類型的元素的集合。一個ndarray數組幾乎是一個Python列表的擴展,但它的操作更加靈活和高效。對於這個類型,有幾個重要的屬性需要了解:
import numpy as np nd = np.array([1, 2, 3, 4]) print(nd.ndim) # 維度數 print(nd.shape) # 各個維度的元素數量 print(nd.size) # 元素總數 print(nd.dtype) # 元素數據類型
其中,ndim、shape、size這三個屬性以及dtype數據類型屬性是我們必須知道的。
二、創建ndarray數組
ndarray數組可以從Python列表、元組、數組等進行創建。
# 從Python列表創建ndarray數組 nd1 = np.array([1, 2, 3]) # 從Python元組創建ndarray數組 nd2 = np.array((1, 2, 3)) # 通過numpy中的方法創建ndarray數組 nd3 = np.arange(10) # array([0, 1, 2, ..., 9]) nd4 = np.zeros((2, 3)) # 2行3列的全0矩陣 nd5 = np.ones((2, 3)) # 2行3列的全1矩陣 nd6 = np.eye(3) # 3行3列的單位矩陣 nd7 = np.random.random((2, 2)) # 隨機2行2列的數組
三、ndarray數組的索引和切片
ndarray中的元素可以通過它們在數組中的位置進行訪問,該位置是由數組的整數索引標誌。可以使用切片符號『:』來獲取部分數組。下面的代碼展示了如何對ndarray數組進行索引和切片。
# 一維數組的索引和切片 nd1 = np.array([1, 2, 3]) print(nd1[0]) # 1 print(nd1[1:3]) # [2 3] # 二維數組的索引和切片 nd2 = np.array([[1, 2, 3], [4, 5, 6]]) print(nd2[1, 2]) # 6 print(nd2[1, :]) # [4 5 6] print(nd2[:, 2]) # [3 6]
四、數組的運算與變形
numpy中可以對ndarray數組進行各種基本的數學操作、運算、變形等。下面的示例展示了一些基本的示例操作。
nd1 = np.array([1, 2, 3]) nd2 = np.array([2, 3, 4]) # 數組加法 print(nd1 + nd2) # [3 5 7] # 數組乘法 print(nd1 * nd2) # [2 6 12] # 數組變形 nd3 = np.array([[1, 2], [3, 4]]) print(nd3.reshape(1, 4)) # [[1 2 3 4]] # 數組求和 print(nd3.sum(axis=0)) # [4 6] print(nd3.sum(axis=1)) # [3 7]
五、線性代數
numpy提供了許多操作矩陣和向量操作的函數,可以方便的進行線性代數計算,例如計算行列式、矩陣乘法、逆矩陣等操作。
a = np.array([[1, 2], [3, 4]]) b = np.array([[4, 5], [6, 7]]) c = np.dot(a, b) # 矩陣乘法 print(c) # [[16, 19], [36, 43]] d = np.linalg.det(a) # 行列式 print(d) # -2.0 e = np.linalg.inv(a) # 逆矩陣 print(e) # [[-2. , 1. ], [ 1.5, -0.5]]
總結
本文簡單介紹了numpy庫中最重要的概念:ndarray。我們學習了ndarray的基本屬性、創建方式、索引和切片、數組運算與變形以及線性代數等方面的操作。掌握了這些知識,我們可以更加高效、方便地處理數組、矩陣等數據類型。numpy的強大之處在於其底層的優化操作,使得我們可以在處理大規模數組時,得到快速、高效的操作及計算結果。
原創文章,作者:MUKS,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/146039.html