Python - Slicing NumPy Arrays

Example: Slicing a 1-D array
x = np.array([5, 10, 15, 20, 25, 30, 35])
print(x[1])  # Indexing
print(x[1:6]) # Slicing
print(x[1:6:3]) # Slicing
Output of Example
10
[10 15 20 25 30]
[10 25]
Example: Slicing a 2-D array
import numpy as np
y = np.array([[0, 1, 2],
              [3, 4, 5]])
print(y[1:2, 1:3]) 
print(y[1])   
print(y[:, 1]) 
Output
[[4 5]]
[3 4 5]
[1 4]
Example: Slicing a n-D array
z = np.array([[[-1, 1], [-2, 2]],
              [[-4, 4], [-5, 5]],
              [[-7, 7], [-9, 9]]])
print(z[1,:,1]) # index 1 element in row of index 1
print(z[1:,1,:]) # From all outer rows except the first, select 1st index element (which itself is an array) completely.
print(z[2]) # print 2nd index element
Output
[4 5]
[[-5  5]
 [-9  9]]
[[-7  7]
 [-9  9]]


No comments:

Post a Comment