Python | 在Numpy中使用argsort方法进行排序

argsort() 是 NumPy 库中的一个函数,它的功能是对数组中的元素进行从小到大的排序,并返回相应元素的原始数组下标。这些下标可以用来以排序顺序重新构造原数组或获取排序后数组元素的原始位置。

具体来说,当你对一个 NumPy 数组调用 argsort() 函数时,它会返回一个新的数组,这个新数组的元素是原数组元素排序后的索引。例如,如果原数组是 [2, 1, 4, 3],那么 argsort() 会返回 [1, 0, 3, 2],因为 1 是原数组中的最小元素,其索引是 1;2 是第二小的元素,其索引是 0;以此类推。

此外,argsort() 函数还可以接受一个可选参数 axis,用于指定排序的轴。如果 axis 被设置为 0,则按列排序;如果 axis 被设置为 1,则按行排序。如果省略该参数,则默认按行排序。

import numpy as np  
  
x = np.array([2, 1, 4, 3])  
y = np.argsort(x)  
print(y)  # 输出 [1 0 3 2]

以上代码中,argsort() 函数对数组 x 中的元素进行排序,并返回排序后的索引数组 y。然后,print() 函数将索引数组打印到控制台上。

使用负索引切片排序

import numpy as np
arr = np.array([5, 2, 8, 3, 6, 10])

# get the indices that would sort the array in ascending order
ascending_indices = arr.argsort() # [1 3 0 4 2 5]

# reverse the ascending indices to get descending indices
descending_indices = ascending_indices[::-1] # [5 2 4 0 3 1]

# use the descending indices to get the elements in descending order
sorted_elements_descending = arr[descending_indices] # [10 8 6 5 32]

print("Sorted Indices (Descending):", descending_indices)
print("Sorted Elements (Descending):", sorted_elements_descending)

输出

Sorted Indices (Descending): [5 2 4 0 3 1] 
Sorted Elements (Descending): [10 8 6 5 3 2]

通过对NumPy数组取反排序

在这个例子中,我们对NumPy数组取反,使用numy.argsort()按降序对其进行排序。在这里,我们将使用argsort()来获取索引,这些索引将按升序对原始数组进行排序。现在,为了获得按降序排序数组的索引,我们首先使用-arr对数组求反,然后对求反后的数组使用argsort()来按降序获得索引。

import numpy as np
arr = np.array([8, 2, 5, 7, 10, 4])

# get the indices that would sort the array in ascending order
ascending_indices = arr.argsort()

# getting the indices that sort the array in descending order by negating the array and sorting it
descending_indices = (-arr).argsort()

# Use the descending indices to get the elements in descending order
sorted_elements_descending = arr[descending_indices]

print("Sorted Indices (Descending):",descending_indices)
print("Sorted Elements (Descending):",sorted_elements_descending)

输出

Sorted Indices (Descending): [4 0 3 2 5 1]
Sorted Elements (Descending): [10 8 7 5 4 2]

使用np.flip方法排序

np.flip 是 NumPy 库中的一个函数,用于翻转数组中的元素。这个函数可以沿着指定的轴翻转数组,如果不指定轴,则默认在所有轴上进行翻转。在大多数情况下,它常用于一维数组或二维数组(矩阵)的翻转。

import numpy as np 

arr = np.array([8, 4, 10, 3, 6])

# get the indices that sort the array in ascending order
sorted_indices = np.argsort(arr)

# reversing the order of elements
sorted_indices_descending = np.flip(sorted_indices)

# get the elements corresponding to sorted indices in descending order
sorted_elements = arr[sorted_indices_descending]

print("Sorted Indices (Descending):",sorted_indices_descending)
print("Sorted Elements (Descending):",sorted_elements)

输出

Sorted Indices (Descending): [2 0 4 1 3]
Sorted Elements (Descending): [10 8 6 4 3] 
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值