訪問多維NumPy陣列不同列的程式


NumPy是 Python 中用於計算數值資料的強大庫。它提供了多維陣列,以及用於處理陣列的不同函式和模組集合。其高效的陣列運算、廣播功能以及與其他庫的整合,使其成為資料處理、分析和建模任務的首選。以下是 NumPy 庫的關鍵特性和功能。

  • 多維陣列

  • 陣列建立

  • 陣列運算

  • 索引和切片

  • 向量化運算

  • 數值例程

  • 與其他庫整合

  • 效能

  • 開源和社群支援

建立陣列

在 NumPy 庫中,我們有稱為array()reshape()的函式。其中array()函式建立一維陣列,而reshape()函式將給定的元素列表轉換為定義的形狀。

示例

在此示例中,我們將使用array()函式透過傳遞元素列表來建立二維陣列,並使用reshape()函式透過傳遞陣列的形狀(即行數和列數)來建立二維陣列。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))

輸出

array: [[90 56 14 22  1]
 [21  7 12  5 24]]
dimension of the array: 2

有多種方法可以訪問多維陣列的不同列。讓我們詳細瞭解每一種方法。

使用基本索引

我們可以使用帶方括號的基本索引來訪問 NumPy 陣列的特定列,其中我們在方括號內指定列索引以檢索所需的列或列。

示例

在此示例中,我們將基本索引方法應用於二維陣列,以使用[:, 0]訪問陣列的第一列,然後它將返回二維陣列的第一列元素。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))
print("The first column of the array:",arr[:,0])

輸出

array: [[90 56 14 22  1]
[21  7 12  5 24]]
dimension of the array: 2
The first column of the array: [90 21]

使用切片

切片用於從給定的輸入陣列訪問一系列列,其中我們必須指定起始和結束索引,以及用冒號分隔的步長。

示例

在此示例中,我們透過使用切片技術應用 [:, 3:5] 來訪問輸入陣列的中間兩列,它將返回中間列元素作為輸出。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))
print("The middle columns of the array:",arr[:,3:5])

輸出

array: [[90 56 14 22  1]
 [21  7 12  5 24]]
dimension of the array: 2
The middle columns of the array: [[22  1]
 [ 5 24]]

使用花式索引

花式索引允許我們透過提供列索引陣列來訪問特定列。當我們想要訪問非連續列或列的特定子集時,可以使用此方法。

示例

在此示例中,我們透過使用花式索引應用索引列表 [:, 0, 4] 來訪問第一列和最後一列,然後它將返回陣列的最後一列和第一列元素。

import numpy as np
l = [90,56,14,22,1,21,7,12,5,24]
arr = np.array(l).reshape(2,5)
print("array:",arr)
print("dimension of the array:",np.ndim(arr))
print("The first and last columns of the array:",arr[:,[0,4]])

輸出

array: [[90 56 14 22  1]
 [21  7 12  5 24]]
dimension of the array: 2
The first and last columns of the array: [[90  1]
 [21 24]]

更新於: 2023年8月2日

92 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.