zoukankan      html  css  js  c++  java
  • numpy-排序

    numpy 有多种排序方法。

    sort

    sort(self, axis=-1, kind='quicksort', order=None):排完序后改变原值  【只有这个方法改变原值】

    axis : int, optional
                    Axis along which to sort. Default is -1, which means sort along the
                    last axis.
    kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
                    Sorting algorithm. Default is 'quicksort'.
    order : str or list of str, optional
                    When `a` is an array with fields defined, this argument specifies
                    which fields to compare first, second, etc.  A single field can
                    be specified as a string, and not all fields need be specified,
                    but unspecified fields will still be used, in the order in which
                    they come up in the dtype, to break ties.

    示例

    a=np.arange(1,5)
    print(a)    # [1 2 3 4]
    
    a.sort()
    print(a)    # [1 2 3 4]
    
    b=np.array([[1,5,3],[4,2,7]])
    b.sort()
    print(b)    # [[1 3 5]
                  # [2 4 7]]
    b=np.array([[1,5,3],[4,2,7]])
    b.sort(axis=0, kind='quicksort')
    print(b)        # [[1 2 3]
                      # [4 5 7]]
    
    # b=np.array([[1,5,3],[4,2,7]])
    # b.sort(axis=0,kind='quicksort',order=None)
    # print(b)
    
    # 参数:
    # axis=0 表示按列 1 表示按行;默认是1按行排序
    # kind 排序的算法,提供了快排(quicksort)、混排、堆排

    np.sort

    sort(a, axis=-1, kind='quicksort', order=None):用法同 sort,但是不改变原值

    c=np.array([[1,5,3],[4,2,7]])
    print(np.sort(c))   # [[1 3 5]
                        # [2 4 7]]
    print(np.sort(c,axis=0))    # [[1 2 3]
                                 # [4 5 7]]
    
    print(c)        # [[1 5 3]      原值没变
                     # [4 2 7]]

    np.argsort

    argsort(self, axis=-1, kind='quicksort', order=None):返回排序后的索引

    # 一维数组
    data5 = np.array([1, 5, 3])
    print data5.argsort()            # [0 2 1]  升序
    print np.argsort(data5)          # [0 2 1]
    print np.argsort(-data5)         # [1 2 0]  降序
    
    
    # 二维数组
    data6 = np.array([[1,2,3],[4,5,6],[0,0,1]])
    # [[1 2 3]
    #  [4 5 6]
    #  [0 0 1]]
    print np.argsort(data6, axis=1)   # 按行排序
    # [[0 1 2]
    #  [0 1 2]
    #  [0 1 2]]
    print np.argsort(data6, axis=0)    # 按列排序
    # [[2 2 2]
    #  [0 0 0]
    #  [1 1 1]]
    
    a_arg = np.argsort(data6[:,1])  # 按第'1'列排序
    print a_arg                     # [2 0 1]   第2个排1,第0个排2,第1个排3
    a = data6[a_arg]
    print a
    # [[0 0 1]
    #  [1 2 3]
    #  [4 5 6]]
  • 相关阅读:
    Spring中的资源加载
    分布式系统Paxos算法
    MySQL中MyISAM与InnoDB区别及选择(转)
    Unable to construct api.Node object for kubelet: can't get ip address of node master.example.com: lookup master.example.com on : no such host
    分库情况下的数据库连接注入
    Core源码(二) Linq的Distinct扩展
    B-Tree详解
    C#进阶之路(八)集合的应用
    重温CLR(十八) 运行时序列化
    重温CLR(十七)程序集加载和反射
  • 原文地址:https://www.cnblogs.com/yanshw/p/11382680.html
Copyright © 2011-2022 走看看