Sorting Numpy Arrays

The numpy.sort() function is used in Numpy to sort arrays in a sequence. This sequence can be ascending or descending. Here, we will see how to,

  • Sort a One-Dimensional Integer Array
  • Sort a One-Dimensional String Array
  • Sort a Two-Dimensional Array

Sort a 1D Numpy Integer array

We will create an array in Numpy with integer elements using the numpy.array() method. To sort it, the numpy.sort() method will be used. Let us see an example:

import numpy as np

# Create a 1D integer array
n = np.array([50, 25, 35, 15, 55, 75, 65, 60, 30, 45])

print("Iterating array...")
for a in n:
    print(a)

# Sort the array using the sort() method
print("\nSorted array = ", np.sort(n))

Output

Iterating array...
50
25
35
15
55
75
65
60
30
45

Sorted array =  [15 25 30 35 45 50 55 60 65 75]

Sort a 1D Numpy string array

We will create an array in Numpy with string elements using the numpy.array() method. To sort it, the numpy.sort() method will be used. Let us see an example:

import numpy as np

# Create a Numpy strungs array
n = np.array(['java', 'keras', 'android', 'express', 'jquery'])

print("Iterating array...")
for a in n:
    print(a)

# Sort the array
print("\nSorted array = ", np.sort(n))

Output

Iterating array...
java
keras
android
express
jquery

Sorted array =  ['android' 'express' 'java' 'jquery' 'keras']

Sort a 2D array

A 2D array gets sorted individually using the sort() function. Let us see an example:

import numpy as np

# Create Numpy 2d array
n = np.array([[5, 3, 7, 9, 6], [15, 25, 13, 20, 12]])

print("Iterating 2D array...")
for a in n:
    print(a)

# Sort the array
print("\nSorted 2D array =\n ", np.sort(n))

Output

Iterating 2D array...
[5 3 7 9 6]
[15 25 13 20 12]

Sorted 2D array =
  [[ 3  5  6  7  9]
 [12 13 15 20 25]]

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.

For Videos, Join Our YouTube Channel: Join Now


Read More:

Search a Numpy Array for a value
Axes in Numpy arrays
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment