当前位置:   article > 正文

【Python】numpy中argsort函数的使用_python中如何用np.argsort输入降序结果

python中如何用np.argsort输入降序结果

1、概述

argsort()函数在模块numpy.core.fromnumeric中。

函数形式是:

  1. help (numpy.argsort)
  2. Help on function argsort in module numpy.core.fromnumeric:
  3. argsort(a, axis=-1, kind='quicksort', order=None)
  4. Returns the indices that would sort an array.
  5. Perform an indirect sort along the given axis using the algorithm specified
  6. by the `kind` keyword. It returns an array of indices of the same shape as
  7. `a` that index data along the given axis in sorted order.
  8. Parameters
  9. ----------
  10. a : array_like
  11. Array to sort.
  12. axis : int or None, optional
  13. Axis along which to sort. The default is -1 (the last axis). If None,
  14. the flattened array is used.
  15. kind : {'quicksort', 'mergesort', 'heapsort'}, optional
  16. Sorting algorithm.
  17. order : str or list of str, optional
  18. When `a` is an array with fields defined, this argument specifies
  19. which fields to compare first, second, etc. A single field can
  20. be specified as a string, and not all fields need be specified,
  21. but unspecified fields will still be used, in the order in which
  22. they come up in the dtype, to break ties.
  23. Returns
  24. -------
  25. index_array : ndarray, int
  26. Array of indices that sort `a` along the specified axis.
  27. If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.

argsort()函数返回的是数组值从小到大的索引值。

排序后会产生一个新的数组,不改变原有的数组。

2、使用

一维数组

  1. a = array([1,4,9,3,2,3,8])
  2. b = a.argsort()
  3. print(a)
  4. print(b)
  5. output:
  6. [1 4 9 3 2 3 8]
  7. [0 4 3 5 1 6 2]
二维数组

  1. x = array([[0, 3], [1, 2]])
  2. print(x)
  3. # [[0 3]
  4. # [1 2]]
  5. b = argsort(x) #默认按最后一维(列)排序
  6. print(b)
  7. # [[0 1]
  8. # [0 1]]
  9. c = argsort(x, axis=0) #按行排序
  10. print(c)
  11. # [[0 1]
  12. # [1 0]]
  13. d = argsort(x, axis=1) #按列排序
  14. print(d)
  15. # [[0 1]
  16. # [0 1]]

其他使用示例:

  1. x = array([1,3,2])
  2. print(x)
  3. # [1 3 2]
  4. b = argsort(x) #按升序排列
  5. print(b)
  6. #[0 2 1]
  7. c = argsort(-x) #按降序排列
  8. print(c)
  9. # [1 2 0]
  10. d = x[argsort(x)] #排序后的数组
  11. print(d)
  12. # [1 2 3]

3、argsort()[num]使用

 z = argsort(x)[num] 与 y = arfsort(x)  z = y[sum]结果相同

  1. x = array([1,3,2])
  2. y = argsort(x)
  3. print(y[1])
  4. # 2
  5. z = argsort(x)[1]
  6. print(z)
  7. # 2

  1. y = argsort(x)
  2. print(y[-1])
  3. # 1
  4. z = argsort(x)[-1]
  5. print(z)
  6. # 1








声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/638678
推荐阅读
相关标签
  

闽ICP备14008679号