在各种数据分析时,排序和去重是用的最多 的两个方法,小白最近也经常用到,这里做一个总结。
目录
首先创造一个array:
a=np.random.random((1,10))
1.排序函数sort
用法:sort(axis=-1, kind='quicksort', order=None)
返回排序的结果
看下官方文档对各个参数的解释:
axis: 排序沿数组的(轴)方向,0表示按行,1表示按列,None表示展开来排序,默认值为-1,表示沿最后的轴排序
kind:排序的算法,提供了快排'quicksort'、混排'mergesort'、堆排'heapsort', 默认为‘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'}, 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.sort()
np.sort(a)
排序前:
array([[0.31960329, 0.43476979, 0.29540886, 0.92095158, 0.44468067,
0.30112425, 0.14642761, 0.15287686, 0.75562827, 0.44646024]])
排序后:
array([[0.14642761, 0.15287686, 0.29540886, 0.30112425, 0.31960329,
0.43476979, 0.44468067, 0.44646024, 0.75562827, 0.92095158]])
2.排序函数argsort
用法:numpy.argsort(a, axis=-1, kind='quicksort', order=None)
对数组沿给定轴执行间接排序,并使用指定排序类型返回数据的索引数组。 这个索引数组用于构造排序后的数组。
参数与sort基本一致,就不再多做说明。
a=np.random.random((1,10))
b=np.argsort(a)
排序前:
array([[0.89723178, 0.21546264, 0.78598617, 0.49631093, 0.69961311,
0.17628665, 0.53010644, 0.80373367, 0.72986822, 0.112973 ]])
排序后b的值:返回的时排序的值的索引,默认是升序排列
array([[9, 5, 1, 3, 6, 4, 8, 2, 7, 0]], dtype=int64)
降序排列:
np.argsort(-a)
结果为:
array([[0, 7, 2, 8, 4, 6, 3, 1, 5, 9]], dtype=int64)
3.去重函数unique
a=[1,2,3,4,5,5,4]#先写一个list
b = np.array(a)#创建一个array
np.unique(b)#去重
结果:
#去重前:
array([1, 2, 3, 4, 5, 5, 4])
#去重后
array([1, 2, 3, 4, 5])
4.查找函数in1d
np.in1d([1,2],b)
结果就是:
array([ True, True])
这个函数要注意的就是d前面的是阿拉伯数字1而不是英文l~
以上就是对array中几个常用函数的介绍啦~