Slicing of NumPy Array

Slicing of NumPy Array

  1. Slicing 1-D NumPy Arrays
  2. Slicing 2-D NumPy Arrays
  3. Slicing 3-D NumPy Arrays
  4. Negative Slicing of NumPy Arrays

Slicing 1-D NumPy Arrays

Program

import numpy as np

ary1d = np.array([2,4,6,8,10,12])
print("Array is:")
print(ary1d)
#Slicing on 1-D Array
s = slice(1,len(ary1d),2)
print("1-D Array elements based on slicing:")
print(ary1d[s])

Output

Array is:
[ 2 4 6 8 10 12]
1-D Array elements based on slicing:
[ 4 8 12]

Slicing 2-D NumPy Arrays

Program

import numpy as np

ary2d = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
print("2-D Array is:")
print(ary2d)
#Slicing on 2-D Array
rs = slice(0,len(ary2d))
cs = slice(0,len(ary2d[0]),2)
print("2-D Array elements based on slicing:")
print(ary2d[rs,cs])

Output

2-D Array is:
[[ 1 2 3 4]
 [ 5 6 7 8]
 [ 9 10 11 12]]
2-D Array elements based on slicing:
[[ 1 3]
 [ 5 7]
 [ 9 11]]

Slicing 3-D NumPy Arrays

Program

import numpy as np

ary3d = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]])
print("3-D Array is:")
print(ary3d)
#Slicing on 3-D Array
xs = slice(0,len(ary3d))
ys = slice(0,len(ary3d[0]))
zs = slice(0,len(ary3d[0][1]),2)
print("3-D Array elements based on slicing:")
print(ary3d[xs,ys,zs])

Output

3-D Array is:
[[[ 1 2 3]
  [ 4 5 6]]

 [[ 7 8 9]
  [10 11 12]]

 [[13 14 15]
  [16 17 18]]]
3-D Array elements based on slicing:
[[[ 1 3]
  [ 4 6]]

 [[ 7 9]
  [10 12]]

 [[13 15]
  [16 18]]]

Negative Slicing of NumPy Arrays

Program

import numpy as np

ary2d = np.array(np.arange(1,21))
ary2d = ary2d.reshape(4,5)
print("2-D Array is:")
print(ary2d)
#Negative Slicing on 2-D Array
rs = slice(-4,-1,+1)
cs = slice(-1,-3,-1)
print("2-D Array elements based on negative slicing:")
print(ary2d[rs,cs])

Output

2-D Array is:
[[ 1 2 3 4 5]
 [ 6 7 8 9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
2-D Array elements based on negative slicing:
[[ 5 4]
 [10 9]
 [15 14]]