python/sorting_2d_arrays.py

24 lines
954 B
Python

import numpy as np
'''
array_2d = np.array([[2, 9, 3], [1, 6, 4], [5, 7, 8]])
# Sorting a 2D array along axis 1
print(np.sort(array_2d))
# Sorting a 2D array along axis 0
print(np.sort(array_2d, axis=0)[::-1])
# Creating a 1D sorted array out of the elements of array_2d
print(np.sort(array_2d, axis=None))
'''
# Simulated exam scores for three students in three subjects
exam_scores = np.array([[75, 82, 90], [92, 88, 78], [60, 70, 85], [80, 95, 88], [70, 65, 80], [85, 90, 92]])
# Create an array with every column sorted by scores in descending order
top_scores_subject = np.sort(exam_scores, axis=0)[::-1]
# Create a 1D array of all scores sorted in ascending order
sorted_scores = np.sort(exam_scores, axis=None)
print("Top scores by subject:")
print(top_scores_subject)
print("All scores sorted (ascending):")
print(sorted_scores)
print("Average score:", sum(sorted_scores) / len(sorted_scores)) # Length of the first dimension (number of rows)