Q6.1.5Indexing and slicing a NumPy array
A \(3\times 4 \times 4\) array is created with:
a = np.linspace(1,48,48).reshape(3,4,4)
Index or slice this array to obtain the following
(a)
20.0
(b)
[ 9. 10. 11. 12.]
(c) The \(4 \times 4\) array:
[[ 33. 34. 35. 36.]
[ 37. 38. 39. 40.]
[ 41. 42. 43. 44.]
[ 45. 46. 47. 48.]]
(d) The \(3 \times 2\) array:
[[ 5. 6.]
[ 21. 22.]
[ 37. 38.]]
(e) The \(4 \times 2\) array:
[[ 36. 35.]
[ 40. 39.]
[ 44. 43.]
[ 48. 47.]]
(f) The \(3 \times 4\) array:
[[ 13. 9. 5. 1.]
[ 29. 25. 21. 17.]
[ 45. 41. 37. 33.]]
(g) (Harder) Using an array of indexes, the \(2 \times 2\) array:
[[ 1. 4.]
[ 45. 48.]]
Show solution
Indexing and slicing a NumPy array:
(a) a[1,0,3]
(b) a[0,2,:] (or just a[0,2])
(c) a[2,...] (or a[2,:,:] or a[2])
(d) a[:,1,:2]
(e) a[2,:,:1:-1] ("in the third block, for each row take the items in the middle two columns'').
(f) a[:,::-1,0] ("for each block, traverse the rows backwards and take the item in the first column of each'').
(g) Defining the three \(2\times 2\) index arrays for the blocks, rows and columns locating our elements as follows:
ia = np.array([[0, 0], [2, 2]])
ja = np.array([[0, 0], [3, 3]])
ka = np.array([[0, 3], [0, 3]])
a[ia,ja,ka] returns the desired result.