Различные методы сортировки строки в массиве NumPy

Чтобы отсортировать строку в массиве NumPy, вы можете использовать различные методы, доступные в библиотеке NumPy. Вот несколько примеров:

Метод 1: использование np.sort()

import numpy as np
# Create a NumPy array
arr = np.array([[3, 2, 1],
                [6, 5, 4],
                [9, 8, 7]])
# Sort the second row
sorted_row = np.sort(arr[1])
print(sorted_row)

Выход:

[4 5 6]

Метод 2: использование argsort()

import numpy as np
# Create a NumPy array
arr = np.array([[3, 2, 1],
                [6, 5, 4],
                [9, 8, 7]])
# Get the indices that would sort the second row
sorted_indices = np.argsort(arr[1])
# Sort the second row based on the indices
sorted_row = arr[1, sorted_indices]
print(sorted_row)

Выход:

[4 5 6]

Метод 3. Использование необычной индексации

import numpy as np
# Create a NumPy array
arr = np.array([[3, 2, 1],
                [6, 5, 4],
                [9, 8, 7]])
# Get the indices that would sort the second row
sorted_indices = np.argsort(arr[1])
# Sort the entire array based on the indices
sorted_arr = arr[:, sorted_indices]
print(sorted_arr[1])

Выход:

[4 5 6]

Метод 4: использование numpy.lexsort()

import numpy as np
# Create a NumPy array
arr = np.array([[3, 2, 1],
                [6, 5, 4],
                [9, 8, 7]])
# Sort the second row using lexsort
sorted_row = arr[:, np.lexsort(arr[::-1])]
print(sorted_row[1])

Выход:

[4 5 6]

Метод 5: использование numpy.partition()

import numpy as np
# Create a NumPy array
arr = np.array([[3, 2, 1],
                [6, 5, 4],
                [9, 8, 7]])
# Sort the second row using partition
sorted_row = np.partition(arr[1], range(arr.shape[1]))
print(sorted_row)

Выход:

[4 5 6]