Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Sort Matrix by Row Median
When working with matrices in Python, you may need to sort rows based on their median values. Python's statistics module provides a median() function that can be used with the sort() method's key parameter to achieve this.
Syntax
from statistics import median matrix.sort(key=lambda row: median(row))
Example
Here's how to sort a matrix by row median using a custom function ?
from statistics import median
def median_row(row):
return median(row)
my_matrix = [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]]
print("Original matrix:")
print(my_matrix)
# Calculate median for each row to understand sorting
for i, row in enumerate(my_matrix):
print(f"Row {i}: {row} ? Median: {median(row)}")
my_matrix.sort(key=median_row)
print("\nSorted matrix by row median:")
print(my_matrix)
Original matrix: [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]] Row 0: [43, 14, 27] ? Median: 27 Row 1: [13, 27, 24] ? Median: 24 Row 2: [32, 56, 18] ? Median: 32 Row 3: [34, 62, 55] ? Median: 55 Sorted matrix by row median: [[13, 27, 24], [43, 14, 27], [32, 56, 18], [34, 62, 55]]
Using Lambda Function
You can also use a lambda function for more concise code ?
from statistics import median
my_matrix = [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]]
print("Original matrix:")
print(my_matrix)
# Sort using lambda function
my_matrix.sort(key=lambda row: median(row))
print("Sorted matrix:")
print(my_matrix)
Original matrix: [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]] Sorted matrix: [[13, 27, 24], [43, 14, 27], [32, 56, 18], [34, 62, 55]]
Sorting in Descending Order
To sort by median in descending order, use the reverse=True parameter ?
from statistics import median
my_matrix = [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]]
print("Original matrix:")
print(my_matrix)
# Sort in descending order
my_matrix.sort(key=lambda row: median(row), reverse=True)
print("Sorted matrix (descending):")
print(my_matrix)
Original matrix: [[43, 14, 27], [13, 27, 24], [32, 56, 18], [34, 62, 55]] Sorted matrix (descending): [[34, 62, 55], [32, 56, 18], [43, 14, 27], [13, 27, 24]]
How It Works
The sort() method uses the key parameter to determine the sorting criteria:
The
median()function calculates the middle value of each rowThe
sort()method compares these median values to order the rowsRows with smaller medians appear first in ascending order
The original matrix is modified in-place
Conclusion
Use sort(key=lambda row: median(row)) to sort a matrix by row median values. The statistics.median() function handles the median calculation, while the key parameter tells sort() how to compare rows.
