Numpy学习---Task05---排序搜索计数及集合操作

Task05---排序搜索计数及集合操作

一、排序,搜索和计数

`numpy.sort(a[, axis=-1, kind='quicksort', order=None])`

  • Return a sorted **copy** of an array.
  • axis:排序沿数组的(轴)方向,0表示按行,1表示按列,None表示展开来排序,默认为-1,表示沿最后的轴排序。
  • kind:排序的算法,提供了快排'quicksort'、混排'mergesort'、堆排'heapsort', 默认为‘quicksort'。
  • order:排序的字段名,可指定字段排序,默认为None。
np.random.seed(1)
x = np.random.rand(5,5)*10
x = np.around(x,2)
print(x)
#[[4.17 7.2  0.   3.02 1.47]
# [0.92 1.86 3.46 3.97 5.39]
# [4.19 6.85 2.04 8.78 0.27]
# [6.7  4.17 5.59 1.4  1.98]
# [8.01 9.68 3.13 6.92 8.76]]

print(np.sort(x))
#[[0.   1.47 3.02 4.17 7.2 ]
# [0.92 1.86 3.46 3.97 5.39]
# [0.27 2.04 4.19 6.85 8.78]
# [1.4  1.98 4.17 5.59 6.7 ]
# [3.13 6.92 8.01 8.76 9.68]]

print(np.sort(x,axis=0))
#[[0.92 1.86 0.   1.4  0.27]
# [4.17 4.17 2.04 3.02 1.47]
# [4.19 6.85 3.13 3.97 1.98]
# [6.7  7.2  3.46 6.92 5.39]
# [8.01 9.68 5.59 8.78 8.76]]

dt = np.dtype([('name','S10'),('age',np.int)])
a = np.array([('Jerry',21),("Alexandra",20)],dtype=dt)
print(a)
#[(b'Jerry', 21) (b'Alexandra', 20)]

print(np.sort(a,order='name'))
#[(b'Alexandra', 20) (b'Jerry', 21)]

print(np.sort(a,order='age'))
#[(b'Alexandra', 20) (b'Jerry', 21)]

 `numpy.argsort(a[, axis=-1, kind='quicksort', order=None])`

  • Returns the indices that would sort an array.
  • 对数组沿给定轴执行间接排序,并使用指定排序类型返回数据的索引数组。这个索引数组用于构造排序后的数组。
np.random.seed(1)
x = np.random.randint(0,10,10)
print(x)
#[5 8 9 5 0 0 1 7 6 9]

y = np.argsort(x)
print(y)
#[4 5 6 0 3 8 7 1 2 9]

print(x[y])
#[0 0 1 5 5 6 7 8 9 9]

y = np.argsort(-x)
print(y)
#[2 9 1 7 8 0 3 6 4 5]

print(x[y])
#[9 9 8 7 6 5 5 1 0 0]

np.random.seed(1)
x = np.random.rand(5,5)*10
x = np.around(x,2)
print(x)
#[[4.17 7.2  0.   3.02 1.47]
# [0.92 1.86 3.46 3.97 5.39]
# [4.19 6.85 2.04 8.78 0.27]
# [6.7  4.17 5.59 1.4  1.98]
# [8.01 9.68 3.13 6.92 8.76]]

y = np.argsort(x)
print(y)
#[[2 4 3 0 1]
# [0 1 2 3 4]
# [4 2 0 1 3]
# [3 4 1 2 0]
# [2 3 0 4 1]]

print(np.array([np.take(x[i],np.argsort(x[i])) for i in range(5)]))
#numpy.take(a, indices, axis=None, out=None, mode='raise')沿轴从数组中获取元素。
#[[0.   1.47 3.02 4.17 7.2 ]
# [0.92 1.86 3.46 3.97 5.39]
# [0.27 2.04 4.19 6.85 8.78]
# [1.4  1.98 4.17 5.59 6.7 ]
# [3.13 6.92 8.01 8.76 9.68]]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值