Numpy Array Indexing

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的亂數功能:

In [1]:
import numpy as np
A=np.random.rand(5)
print(A)
[ 0.60973462  0.62291525  0.66852139  0.01154638  0.87972005]

Starting from the beginning (0) or ending at the last can be obmitted

Python陣列位置編號從0開始,如果要取出一個位置範圍的元素且從0開始(arr[0:n]),則0可以省略(arr[:n]) 如果範圍的結尾在最後一個元素(包含它),也可以省略(arr[n:])

The negative index

Python陣列位置編號可以接受負值,-1為最後一個元素,-2為倒數第二個,以此類推(注意:用在範圍的時候,要再-1)

In [7]:
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]

Multi-dimension array

Arr[i,:] = Arr[i] : index a multidimensional array with fewer indices than dimensions will get a subdimensional array

In [3]:
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]

Indice Array

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.

In [4]:
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]
In [5]:
# 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]