Expanding and Squeezing a NumPy Array

Expanding and Squeezing a NumPy Array

  1. Expanding a NumPy Array
  2. Squeezing a NumPy Array
  3. Sorting in NumPy Arrays

Expanding a NumPy Array

Program

import numpy as np

ary = np.array([1,2,3])
print("Array is:")
print(ary)
print("Shape of array is :",ary.shape)
print("Array dimensions :",ary.ndim)

#Expand Array
ary2 = np.expand_dims(ary,axis=0)
print("After expand Array is:")
print(ary2)
print("Shape of array2 is :",ary2.shape)
print("Array2 dimensions :",ary2.ndim)

Output

Array is:
[1 2 3]
Shape of array is : (3,)
Array dimensions : 1
After expand Array is:
[[1 2 3]]
Shape of array2 is : (1, 3)
Array2 dimensions : 2

Squeezing a NumPy Array

Program

import numpy as np

#Creating 1-D and 2-D Arrays
ary1d = np.array([1,2,3])
ary2d = np.array([[1,2,3]])
print("1-D Array is:")
print(ary1d)

#Squeezed 1-D Array
print("Remove axes of length one from 1-D array:")
print(np.squeeze(ary1d))
print("Shape of 1-D array is :",np.squeeze(ary1d).shape)
print("Array dimensions :",np.squeeze(ary1d).ndim)
print("2-D Array is:")
print(ary2d)

#Squeezed 2-D Array
print("Remove axes of length one from 2-D array:")
print(np.squeeze(ary2d))
print("Shape of 2-D array is :",np.squeeze(ary2d).shape)
print("Array dimensions :",np.squeeze(ary2d).ndim)

Output

1-D Array is:
[1 2 3]
Remove axes of length one from 1-D array:
[1 2 3]
Shape of 1-D array is : (3,)
Array dimensions : 1
2-D Array is:
[[1 2 3]]
Remove axes of length one from 2-D array:
[1 2 3]
Shape of 2-D array is : (3,)
Array dimensions : 1

Sorting in NumPy Arrays

Program

import numpy as np

#Creating 1-D Array
ary1d = np.array([4,2,5,1,3])
print("Before sorting 1-D Array is:")
print(ary1d)
#1-D Array Sort
ary1d.sort()
print("After sorting 1-D Array is:")
print(ary1d)

#Creating 2-D Array
ary2d = np.array([[2,3,1,4],[4,0,5,2]])
print("Before sorting 2-D Array is:")
print(ary2d)
#2-D Array Sort
ary2d.sort()
print("After sorting 2-D Array is:")
print(ary2d)

Output

Before sorting 1-D Array is:
[4 2 5 1 3]
After sorting 1-D Array is:
[1 2 3 4 5]
Before sorting 2-D Array is:
[[2 3 1 4]
  [4 0 5 2]]
After sorting 2-D Array is:
[[1 2 3 4]
  [0 2 4 5]]