如何对一个Numpy数组进行排序
在这篇文章中,我们将学习如何对一个Numpy数组进行排序。在Numpy中,有多种方法对数组进行排序,基于使用Python的要求。让我们在不同方法的帮助下尝试了解它们。
方法1:使用sort()对Numpy数组进行排序。
只需使用sort()方法对给定数组进行基于轴的排序。
# importing libraries
import numpy as np
# sort along the first axis
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = 0)
print ("Along first axis : \n", arr1)
# sort along the last axis
a = np.array([[10, 15], [12, 1]])
arr2 = np.sort(a, axis = -1)
print ("\nAlong first axis : \n", arr2)
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = None)
print ("\nAlong none axis : \n", arr1)
输出:
Along first axis :
[[10 1]
[12 15]]
Along first axis :
[[10 15]
[ 1 12]]
Along none axis :
[ 1 10 12 15]
方法2: 使用argsort()对一个Numpy数组进行排序。
使用argsort()方法获得可以返回排序的数组的索引
import numpy as np
# Numpy array created
a = np.array([9, 3, 1, 7, 4, 3, 6])
# unsorted array print
print('Original array:\n', a)
# Sort array indices
b = np.argsort(a)
print('Sorted indices of original array->', b)
# To get sorted array using sorted indices
# c is temp array created of same len as of b
c = np.zeros(len(b), dtype = int)
for i in range(0, len(b)):
c[i]= a[b[i]]
print('Sorted array->', c)
输出:
Original array:
[9 3 1 7 4 3 6]
Sorted indices of original array-> [2 1 5 4 6 3 0]
Sorted array-> [1 3 3 4 6 7 9]
方法3: 使用一个键的序列对Numpy数组进行排序。
使用一连串的键获得稳定的排序。
import numpy as np
# Numpy array created
# First column
a = np.array([9, 3, 1, 3, 4, 3, 6])
# Second column
b = np.array([4, 6, 9, 2, 1, 8, 7])
print('column a, column b')
for (i, j) in zip(a, b):
print(i, ' ', j)
# Sort by a then by b
ind = np.lexsort((b, a))
print('Sorted indices->', ind)
输出:
column a, column b
9 4
3 6
1 9
3 2
4 1
3 8
6 7
Sorted indices-> [2 3 1 5 4 6 0]