Array indexing refers to any use of the square brackets ([]) to index the location of elements in an array. The syntax of index (index array) allows flexibility to extract specific elements from an array.
在Numpy陣列名稱後用[]放入數值,可以取出特定位置的元素,這邊介紹跟元素位置編號相關的幾種進階語法
為了方便舉例,一樣先產生一個長度為5的一維陣列,這邊使用Numpy的亂數功能:
import numpy as np
A=np.random.rand(5)
print(A)
[ 0.60973462 0.62291525 0.66852139 0.01154638 0.87972005]
print(A)
print(A[:3])
print(A[2:])
print(A[-1])
print(A[1:-1])
[ 0.60973462 0.62291525 0.66852139 0.01154638 0.87972005] [ 0.60973462 0.62291525 0.66852139] [ 0.66852139 0.01154638 0.87972005] 0.879720047923 [ 0.62291525 0.66852139 0.01154638]
Arr[i,:] = Arr[i] : index a multidimensional array with fewer indices than dimensions will get a subdimensional array
B=np.random.rand(8).reshape(2,4)
print(B)
print(B[1])
print(B[1][1:-1]) # same (but less efficient) as B[1,1:-1] (generate a new temporary subarray)
[[ 0.94615555 0.08535754 0.38392011 0.04051516] [ 0.82115174 0.07229945 0.36368839 0.93464504]] [ 0.82115174 0.07229945 0.36368839 0.93464504] [ 0.07229945 0.36368839]
NumPy arrays may be indexed with other arrays (lists/tuples).
Use this methods the elements can be extracted multiple times, or not in decreasing/increasing order of index location. Negative index is also allowed.
ind0=[3,1,1,4,-1,0,-2]
print(A)
print(A[ind0])
[ 0.60973462 0.62291525 0.66852139 0.01154638 0.87972005] [ 0.01154638 0.62291525 0.62291525 0.87972005 0.87972005 0.60973462 0.01154638]
# Example for 2-D array (# to extract B[1,0],B[1,1],B[0,2])
ind1=[1,1,0]
ind2=[0,1,2]
print(B)
print(B[ind1,ind2]) # get B[1,0],B[1,1],B[0,2]
[[ 0.94615555 0.08535754 0.38392011 0.04051516] [ 0.82115174 0.07229945 0.36368839 0.93464504]] [ 0.82115174 0.07229945 0.38392011]