NumPy 比一般的 Python 序列提供更多的索引方式。除了之前看到的用整數(shù)和切片的索引外,數(shù)組可以由整數(shù)數(shù)組索引、布爾索引及花式索引。
整數(shù)數(shù)組索引
以下實(shí)例獲取數(shù)組中(0,0),(1,1)和(2,0)位置處的元素。
1
2
3
4
5
|
import numpy as np x = np.array([[ 1 , 2 ], [ 3 , 4 ], [ 5 , 6 ]]) y = x[[ 0 , 1 , 2 ], [ 0 , 1 , 0 ]] print (y) |
輸出結(jié)果為:
[1 4 5]
以下實(shí)例獲取了 4X3 數(shù)組中的四個(gè)角的元素。 行索引是 [0,0] 和 [3,3],而列索引是 [0,2] 和 [0,2]。
1
2
3
4
5
6
7
8
9
10
11
|
import numpy as np x = np.array([[ 0 , 1 , 2 ],[ 3 , 4 , 5 ],[ 6 , 7 , 8 ],[ 9 , 10 , 11 ]]) print ( '我們的數(shù)組是:' ) print (x) print ( '\n' ) rows = np.array([[ 0 , 0 ],[ 3 , 3 ]]) cols = np.array([[ 0 , 2 ],[ 0 , 2 ]]) y = x[rows,cols] print ( '這個(gè)數(shù)組的四個(gè)角元素是:' ) print (y) |
輸出結(jié)果為:
我們的數(shù)組是:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
這個(gè)數(shù)組的四個(gè)角元素是:
[[ 0 2]
[ 9 11]]
返回的結(jié)果是包含每個(gè)角元素的 ndarray 對象。
可以借助切片 : 或 … 與索引數(shù)組組合。如下面例子:
1
2
3
4
5
6
7
8
9
|
import numpy as np a = np.array([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ],[ 7 , 8 , 9 ]]) b = a[ 1 : 3 , 1 : 3 ] c = a[ 1 : 3 ,[ 1 , 2 ]] d = a[..., 1 :] print (b) print (c) print (d) |
輸出結(jié)果為:
[[5 6]
[8 9]]
[[5 6]
[8 9]]
[[2 3]
[5 6]
[8 9]]
布爾索引
我們可以通過一個(gè)布爾數(shù)組來索引目標(biāo)數(shù)組。
布爾索引通過布爾運(yùn)算(如:比較運(yùn)算符)來獲取符合指定條件的元素的數(shù)組。
以下實(shí)例獲取大于 5 的元素:
1
2
3
4
5
6
7
8
9
|
import numpy as np x = np.array([[ 0 , 1 , 2 ],[ 3 , 4 , 5 ],[ 6 , 7 , 8 ],[ 9 , 10 , 11 ]]) print ( '我們的數(shù)組是:' ) print (x) print ( '\n' ) # 現(xiàn)在我們會打印出大于 5 的元素 print ( '大于 5 的元素是:' ) print (x[x > 5 ]) |
輸出結(jié)果為:
我們的數(shù)組是:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
大于 5 的元素是:
[ 6 7 8 9 10 11]
以下實(shí)例使用了 ~(取補(bǔ)運(yùn)算符)來過濾 NaN。
1
2
3
4
|
import numpy as np a = np.array([np.nan, 1 , 2 ,np.nan, 3 , 4 , 5 ]) print (a[~np.isnan(a)]) |
輸出結(jié)果為:
[ 1. 2. 3. 4. 5.]
以下實(shí)例演示如何從數(shù)組中過濾掉非復(fù)數(shù)元素。
1
2
3
4
|
import numpy as np a = np.array([ 1 , 2 + 6j , 5 , 3.5 + 5j ]) print (a[np.iscomplex(a)]) |
輸出如下:
[2.0+6.j 3.5+5.j]
花式索引
花式索引指的是利用整數(shù)數(shù)組進(jìn)行索引。
花式索引根據(jù)索引數(shù)組的值作為目標(biāo)數(shù)組的某個(gè)軸的下標(biāo)來取值。對于使用一維整型數(shù)組作為索引,如果目標(biāo)是一維數(shù)組,那么索引的結(jié)果就是對應(yīng)位置的元素;如果目標(biāo)是二維數(shù)組,那么就是對應(yīng)下標(biāo)的行。
花式索引跟切片不一樣,它總是將數(shù)據(jù)復(fù)制到新數(shù)組中。
1、傳入順序索引數(shù)組
1
2
3
4
|
import numpy as np x = np.arange( 32 ).reshape(( 8 , 4 )) print (x[[ 4 , 2 , 1 , 7 ]]) |
輸出結(jié)果為:
[[16 17 18 19]
[ 8 9 10 11]
[ 4 5 6 7]
[28 29 30 31]]
2、傳入倒序索引數(shù)組
1
2
3
4
|
import numpy as np x = np.arange( 32 ).reshape(( 8 , 4 )) print (x[[ - 4 , - 2 , - 1 , - 7 ]]) |
輸出結(jié)果為:
[[16 17 18 19]
[24 25 26 27]
[28 29 30 31]
[ 4 5 6 7]]
3、傳入多個(gè)索引數(shù)組(要使用np.ix_)
1
2
3
4
|
import numpy as np x = np.arange( 32 ).reshape(( 8 , 4 )) print (x[np.ix_([ 1 , 5 , 7 , 2 ],[ 0 , 3 , 1 , 2 ])]) |
輸出結(jié)果為:
[[ 4 7 5 6]
[20 23 21 22]
[28 31 29 30]
[ 8 11 9 10]]
以上就是深入了解NumPy 高級索引的詳細(xì)內(nèi)容,更多關(guān)于NumPy 高級索引的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://www.runoob.com/numpy/numpy-advanced-indexing.html