Wednesday, May 27, 2020

Numpy Array Slicing

NumPy Array Slicing


Array Slicing


Python supports slicing, it means taking a chunk or piece from the given array starting from a specified start index position to the specified end index position. We can also mention a step size. NumPy array slicing works very much similar to the Python slicing. Slices are references to the original memory references in the array. If any change is made in the slice will be reflected in the original array.

We can define a slice like this: [start: end] 

Or 

with a step included like this: [start:end: step] 

If the start is not specified it is considered 0, If the end is not specified it is considered equal to the length of the array in that dimension. If the step is not mentioned it will be considered 1 automatically.

For example,

import numpy as np
nums = np.array([12,1,7,43,10,7,12,45])
#Slice an array using [START:END:STEP]
print(nums[3:5]) #4th, 5th items
print(nums[2:]) #3rd item to last
print(nums[:]) # all items
print(nums[-3:-1]) #Last two items(negative indexing)
#slice using steps
print(nums[1:6:2]) # stepsize 2
print(nums[::2]) #Alternate items(odd postions)
print(nums[1::2]) #Alternate items(even positions)
print(nums[::]) #Alternate items
 
#Output
[43 10]
[ 7 43 10  7 12 45]
[12  1  7 43 10  7 12 45]
[ 7 12]
[ 1 43  7]
[12  7 10 12]
[ 1 43  7 45]
[12  1  7 43 10  7 12 45]

Slicing 2-D array


A 2-D array can be easily sliced.

import numpy as np
nums = np.array([[12,10,5],[7,13,71],[22,53,25]])
#Slice 2-D array
print(nums[1,0:3]) #Second row [ 7 13 71]
print(nums[0:3,1]) #secod column [10 13 53]
OR,


import numpy as np
nums = np.array([[12,10,5,10],[7,50,13,71],[22,20,53,25],[1,15,3,5],[5,35,13,78],[5,78,23,32]])
# 2-D array
print(nums)
print(nums[0:5:2, 0::2])

#Output
[[12 10  5 10]
 [ 7 50 13 71]
 [22 20 53 25]
 [ 1 15  3  5]
 [ 5 35 13 78]
 [ 5 78 23 32]]
[[12  5]
 [22 53]
 [ 5 13]]


Slicing 3-D array


import numpy as np
nums = np.array([[[12,10,5],[7,13,71]],[[22,53,25],[1,3,5]],[[5,13,78],[78,23,32]]])
#Slice 3-D array
print(nums[0,0, 0:3]) #[12 10  5]
print(nums[0:3,1,1])  #[13  3 23]

Strides


Every dimension of an ndarray is accessed by stepping (striding) a fixed number of bytes through memory. If memory is contiguous, then the strides are “pre-computed” indexing-formulas for either Fortran-order (first-dimension varies the fastest) or C-order (last-dimension varies the fastest) arrays.

import numpy as np
nums = np.array([[12,10,5,10],[7,50,13,71],[22,20,53,25],[1,15,3,5]])
#Strides
print(nums.strides) 

#Output
(32,8)