Array (Slicing)
Array (Slicing)
Slicing arrays
Slicing in python means taking elements from one given index to another given
index.
We pass slice instead of index like this: [start:end].
We can also define the step, like this: [start:end:step].
If we don't pass start its considered 0
If we don't pass end its considered length of array in that dimension
If we don't pass step its considered 1
import numpy as np
print(arr[0:3])
[1 2 3]
import numpy as np
print(arr[4:])
[5 6 7]
import numpy as np
Array (Slicing) 1
print(arr[:4])
[1 2 3 4]
#Negative Slicing
#Use the minus operator to refer to an index from the end:
import numpy as np
print(arr[-3:-1])
[5 6]
#STEP
#Use the step value to determine the step of the slicing:
#Return every other element from the entire array:
import numpy as np
print(arr[0::3])
[ 1 4 7 10]
import numpy as np
print(arr[0:7:2])
[1 3 5 7]
Array (Slicing) 2
import numpy as np
print(arr[0:2, 1:4])
[[2 3 4]
[7 8 9]]
import numpy as np
print(arr[0:3, 2:4])
[[3 4]
[8 9]
[4 5]]
#From both elements, slice index 1 to index 4 (not included), this will return a 2-D
array:
import numpy as np
print(arr [0:2,1:4])
[[2 3 4]
[7 8 9]]
Array (Slicing) 3