0
0
NumPydata~5 mins

Sorting along axes in NumPy

Choose your learning style9 modes available
Introduction

Sorting data helps us organize numbers or values in order. Sorting along axes means arranging data row-wise or column-wise in arrays.

You want to find the smallest or largest values in each row or column of a table.
You need to organize data in a spreadsheet by rows or columns for easier reading.
You want to prepare data for analysis by sorting each feature separately.
You want to compare sorted values across rows or columns.
You want to quickly find median or quartiles along rows or columns.
Syntax
NumPy
numpy.sort(a, axis=-1, kind='quicksort', order=None)

a is the input array to sort.

axis decides which direction to sort: 0 for rows, 1 for columns, -1 for last axis (default).

Examples
This sorts each row individually in ascending order.
NumPy
import numpy as np
arr = np.array([[3, 1, 2], [6, 4, 5]])
sorted_arr = np.sort(arr, axis=1)
print(sorted_arr)
This sorts each column individually in ascending order.
NumPy
import numpy as np
arr = np.array([[3, 1, 2], [6, 4, 5]])
sorted_arr = np.sort(arr, axis=0)
print(sorted_arr)
Sample Program

This program creates a 2D array and sorts it first by rows, then by columns, showing how sorting along different axes changes the order.

NumPy
import numpy as np

# Create a 2D array
arr = np.array([[10, 3, 5], [7, 8, 2]])

# Sort along rows (axis=1)
sorted_rows = np.sort(arr, axis=1)
print('Sorted along rows:')
print(sorted_rows)

# Sort along columns (axis=0)
sorted_cols = np.sort(arr, axis=0)
print('Sorted along columns:')
print(sorted_cols)
OutputSuccess
Important Notes

Sorting does not change the original array unless you assign the result back.

Use axis=0 to sort each row, axis=1 to sort each column.

Sorting is always in ascending order by default.

Summary

Sorting along axes organizes data row-wise or column-wise.

Use numpy.sort with axis parameter to control direction.

Sorting helps in data analysis by arranging values clearly.