NumPy - 索引與切片



ndarray 物件的內容可以透過索引或切片訪問和修改,就像 Python 的內建容器物件一樣。

如前所述,ndarray 物件中的專案遵循基於零的索引。有三種索引方法可用:欄位訪問、基本切片高階索引

基本切片是 Python 基本切片概念到 n 維的擴充套件。Python 切片物件是透過向內建的 `slice` 函式提供 `start`、`stop` 和 `step` 引數來構造的。此切片物件傳遞給陣列以提取陣列的一部分。

示例 1

import numpy as np 
a = np.arange(10) 
s = slice(2,7,2) 
print a[s]

其輸出如下:

[2  4  6]

在上面的示例中,透過 `arange()` 函式準備了一個 `ndarray` 物件。然後定義一個切片物件,其 `start`、`stop` 和 `step` 值分別為 2、7 和 2。當此切片物件傳遞給 ndarray 時,將切片其從索引 2 開始到 7(不包括 7)的部分,步長為 2。

也可以透過直接在 `ndarray` 物件中使用冒號 `:` 分隔的切片引數 (start:stop:step) 來獲得相同的結果。

示例 2

import numpy as np 
a = np.arange(10) 
b = a[2:7:2] 
print b

這裡,我們將獲得相同的輸出:

[2  4  6]

如果只設置一個引數,則將返回對應於該索引的單個專案。如果在其前面插入一個 `:`,則將提取從該索引開始的所有專案。如果使用兩個引數(用 `:` 分隔),則將切片兩個索引之間的專案(不包括停止索引),預設步長為 1。

示例 3

# slice single item 
import numpy as np 

a = np.arange(10) 
b = a[5] 
print b

其輸出如下:

5

示例 4

# slice items starting from index 
import numpy as np 
a = np.arange(10) 
print a[2:]

現在,輸出將是:

[2  3  4  5  6  7  8  9]

示例 5

# slice items between indexes 
import numpy as np 
a = np.arange(10) 
print a[2:5]

這裡的輸出將是:

[2  3  4] 

以上描述也適用於多維 `ndarray`。

示例 6

import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 
print a  

# slice items starting from index
print 'Now we will slice the array from the index a[1:]' 
print a[1:]

輸出如下:

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

Now we will slice the array from the index a[1:]
[[3 4 5]
 [4 5 6]]

切片還可以包含省略號 (...) 以建立一個與陣列維度長度相同的選擇元組。如果在行位置使用省略號,它將返回一個包含行中專案的 ndarray。

示例 7

# array to begin with 
import numpy as np 
a = np.array([[1,2,3],[3,4,5],[4,5,6]]) 

print 'Our array is:' 
print a 
print '\n'  

# this returns array of items in the second column 
print 'The items in the second column are:'  
print a[...,1] 
print '\n'  

# Now we will slice all items from the second row 
print 'The items in the second row are:' 
print a[1,...] 
print '\n'  

# Now we will slice all items from column 1 onwards 
print 'The items column 1 onwards are:' 
print a[...,1:]

此程式的輸出如下:

Our array is:
[[1 2 3]
 [3 4 5]
 [4 5 6]] 
 
The items in the second column are: 
[2 4 5] 

The items in the second row are:
[3 4 5]

The items column 1 onwards are:
[[2 3]
 [4 5]
 [5 6]] 
廣告