Array Slicing in Python
--
Slicing is used to retrieve set of values from an array.
Slicing on 1-Dimensional Array
It is defined as below
arrayName[start:end:step]
start — Starting Index, inclusive. It could be optional as well, default value is 0.
end — Ending Index, exclusive. It could be optional as well, default value is length of the array.
step — Optional field, it is 1 by default.
Example
array1 = [‘a’, ‘b’, ‘c’,’d’,’e’,’f’]
If we need only the elements b,c,d from the array, then we write as below
array1[1:4]
Output: ['b', 'c', 'd']
where 1 is the starting index, 4 is the ending index which is excluded and step is 1 by default.
array1[1:4:2]
Output: ['b', 'd']array1[1:]
Output: ['b', 'c', 'd', 'e', 'f']array1[:4]
Output: ['a', 'b', 'c', 'd']array1[:]
Output: ['a', 'b', 'c', 'd', 'e', 'f']
Slicing on 2-Dimensional Array
2D Array consists of rows and columns. So, in order to slice a 2D array, we have to perform slicing operation on both rows and columns. The syntax is as below
arrayname[start:end:step, start:end:step]
First one is for rows and second one is for columns
# importing numpy package for creating 2D Array
import numpy as np
#Creating 2D Array
array2 = np.array([[1,2,3,4],
[2,3,4,5],
[3,4,5,6],
[4,5,6,7]
])#Slicing Operation on 2D Array
# to return all rows and only first two columns from the array defined.
array2[:,:2]
Output: array([[1, 2],
[2, 3],
[3, 4],
[4, 5]])
# to return from second row and first two columns
array2[1:,:2]
Output: array([[2, 3],
[3, 4],
[4, 5]])
Happy reading :)