Slicing is the reading and changing multiple values in an array. It is similar to indexing, however indexing is reading and changing of a single value.
Slicing between two positions in array
1 2 3 4 5 6 7 8 9 10 |
# import numpy library as np import numpy as np # Create an array one_dim = np.arange(1, 40, 2) print(one_dim) # Slicing from position 1 to position 5 and not including position 5 print(one_dim[1:5]) |
The above code will output this result
[ 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39]
[3 5 7 9]
Slicing first and last positions in array
1 2 |
# Slicing the first 3 elements print(one_dim[:3]) |
The above code will output this result
[1 3 5]
Slicing last positions in array
1 2 |
# Slicing the last 3 elements print(one_dim[-3:]) |
The above code will output this result
[35 37 39]
Slicing two dimensional array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# import numpy library as np import numpy as np # Create an array two_dim = np.array([[1,2,3], [4,5,6]]) print(two_dim) print() # Slicing from the first row to second position row but not including second. # Slicing from the first column to the third position column not including third print(two_dim[:2,:3]) print() # Slicing all rows and columns from index 1 to index 3 two_dim[:,1:3] |
The above code will output this result
[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
array([[2, 3],
[5, 6]])