Slicing is the way by which we can extract the portion of an array to generate a new array. In this tutorial, we will see how to use slicing on numpy arrays.

For slicing we use a sequence of numbers separated by “:” within square brackets.If we want to slice an array A from index a to index b we use  A[a:b] to slice the required portion. Here a is included while b is excluded. i.e. sliced array will have elements of index a to index b-1 from original array. For example if we  want to slice a portion of an array that starts from  index 2 and goes to index 5 then we will use starting index that is 2 and final index that is 6 separated by “:”.

import numpy as np
A=np.arange(1,10)
print("Array A is:")
print(A)
print("sliced portion of array is")
B=A[2:6]
print(B)

Output:

Array A is:
[1 2 3 4 5 6 7 8 9]
sliced portion of array is
[3 4 5 6]

If we want to extract a portion of the array A in which indexes are separated by an interval then we can do so by specifying starting index a , interval b and stopping index c and then we can use A[a:c:b]. For example, suppose we want to slice elements starting from index 0 and ending at index 8 with an interval of 3, then we can do so by following code.

import numpy as np
A=np.arange(1,10)
print("Array A is:")
print(A)
print("sliced portion of array is")
B=A[0:8:3]
print(B)

Output:

Array A is:
[1 2 3 4 5 6 7 8 9]
sliced portion of array is
[1 4 7]

Slicing 2-D numpy arrays

To slice a 2-D numpy array, we will have to explicitly define intervals for both rows and columns.We can specify intervals for rows and columns in every format we have used for 1-D arrays.

import numpy as np
A=np.arange(1,10).reshape(3,3)
print("Array A is:")
print(A)
print("sliced portion of array is")
B=A[0:2,0:2]
print(B)

Output:

Array A is:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
sliced portion of array is
[[1 2]
 [4 5]]

When we slice arrays from python lists, they are copies, but in numpy, the sliced arrays are views of the same underlying buffer. In other words slices of lists in python are stored in an another location but when we create a slice of numpy arrays, a different view of same memory content is visible to us.

Conclusion

In this tutorial we have seen how to slice 1-d and 2-d numpy arrays using different ways. We have also seen the difference between the slices of python lists and slices of numpy arrays.

References:

Happy Learning!