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]]
原文地址:https://www.cnblogs.com/yanshw/p/11382680.html