Go Python 2: Index Slicing
code 1:
1 import numpy as np 2 3 a = np.arange(15).reshape(3,5) 4 5 print('a:') 6 print(a) 7 print('a[1,2]:') 8 print(a[1,2]) 9 print('a[1]:') 10 print(a[1]) 11 print('a[1,:]:') 12 print(a[1,:]) 13 print('a[1,...]:') 14 print(a[1,...]) 15 print('a[1,1:]:') 16 print(a[1,1:]) 17 print('a[1,1::]:') 18 print(a[1,1::]) 19 print('a[1,:3]:') 20 print(a[1,:3]) 21 print('a[1,3:]:') 22 print(a[1,3:]) 23 print('a[1,3:3]:') 24 print(a[1,3:3]) 25 print('a[1,2:3]:') 26 print(a[1,2:3]) 27 print('a[1,1:3]:') 28 print(a[1,1:3]) 29 print('a[1:2,1:3]:') 30 print(a[1:2,1:3])
result 1:
1 a: 2 [[ 0 1 2 3 4] 3 [ 5 6 7 8 9] 4 [10 11 12 13 14]] 5 a[1,2]: 6 7 7 a[1]: 8 [5 6 7 8 9] 9 a[1,:]: 10 [5 6 7 8 9] 11 a[1,...]: 12 [5 6 7 8 9] 13 a[1,1:]: 14 [6 7 8 9] 15 a[1,1::]: 16 [6 7 8 9] 17 a[1,:3]: 18 [5 6 7] 19 a[1,3:]: 20 [8 9] 21 a[1,3:3]: 22 [] 23 a[1,2:3]: 24 [7] 25 a[1,1:3]: 26 [6 7] 27 a[1:2,1:3]: 28 [[6 7]]
code 2:
1 import numpy as np 2 3 a = np.arange(15).reshape(3,5) 4 b = np.array([0,2,4]) 5 print('a[np.arange(3),b]:') 6 print(a[np.arange(3),b]) 7 a[np.arange(3),b]+=10 8 print('update a:') 9 print(a)
result 2:
1 a[np.arange(3),b]: 2 [ 0 7 14] 3 update a: 4 [[10 1 2 3 4] 5 [ 5 6 17 8 9] 6 [10 11 12 13 24]]
code 3:
1 import numpy as np 2 3 a = np.array([[1,2,3],[3,5,3],[8,2,4],[6,9,1]]) 4 bool_idx = (a>4) 5 6 print('bool_idx:') 7 print(bool_idx) 8 print('a[bool_idx]:') 9 print(a[bool_idx]) 10 print('a[a>4]:') 11 print(a[a>4])
result 3:
1 bool_idx: 2 [[False False False] 3 [False True False] 4 [ True False False] 5 [ True True False]] 6 a[bool_idx]: 7 [5 8 6 9] 8 a[a>4]: 9 [5 8 6 9]