Reputation: 103
In NumPy I understand how to slice 2D arrays from a 3D array using this article:
array = [[[0 1 2]
[3 4 5]
[6 7 8]]
[[9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
Slicing would give me:
i_slice = array[0]
[[0 1 2]
[3 4 5]
[6 7 8]]
j_slice = array[:, 0]
[[0 1 2]
[9 10 11]
[18 19 20]]
k_slice = array[:, :, 0]
[[0 3 6]
[9 12 15]
[18 21 24]]
But is it possible to slice at a 45 degree angle? Such as:
j_slice_down = array[slice going down starting from index 0]
[[0 1 2]
[12 13 14]
[24 25 26]]
I can do this on all 3 axis' going up or down and wrapping around with lists and for loops, but there must be a better way in NumPy.
Upvotes: 8
Views: 2910
Reputation: 231335
In [145]: arr[np.arange(3), np.arange(3),:]
Out[145]:
array([[ 0, 1, 2],
[12, 13, 14],
[24, 25, 26]])
Upvotes: 3
Reputation: 29732
You can try with np.diagonal
:
arr = np.array([[[0 ,1 ,2],
[3 ,4 ,5],
[6 ,7 ,8]],
[[9 ,10 ,11],
[12 ,13 ,14],
[15 ,16 ,17]],
[[18 ,19 ,20],
[21 ,22 ,23],
[24 ,25 ,26]]])
np.diagonal(arr).T
array([[ 0, 1, 2],
[12, 13, 14],
[24, 25, 26]])
Upvotes: 2