numpy基础(part13)--排序

学习笔记,这个笔记以例子为主。
开发工具:Spyder



排序

我们可以简单的,直接的对数组进行排序,并返回有序数组。

  • 语法
有序数组 = np.msort(待排序数组)
  • 例子

代码:

import numpy as np

num = np.array([1, 7, 3, 2, 9, 5, 3])
sorted_num = np.msort(num)
print('排序后数组:', sorted_num)

结果:

排序后数组: [1 2 3 3 5 7 9]

联合间接排序lexsort

联合间接排序支持为主序列进行排序,若存在主序列值相同,则利用次要序列1作为参考继续排序,以此类推,最终返回排序过后的有序索引数组。

  • 语法
indices = numpy.lexsort((次要序列k,..., 次要序列1, 主序列))
  • 例子1

先按照weight排序,再按照age排序,再按照id_num排序。(都是升序排序)

代码:

import numpy as np

names = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G'])

weight = [7, 4, 3, 5, 8, 3, 4]
age  = [8, 7, 2, 3, 8, 3, 7]
id_num = list(range(1, 8))

index_num = np.lexsort((id_num, age, weight))
print(names[index_num])

结果:

['C' 'F' 'B' 'G' 'D' 'A' 'E']
  • 例子2

先按照weight升序排序,再按照age升序排序,再按照id_num降序排序。

代码:

import numpy as np

names = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G'])

weight = [7, 4, 3, 5, 8, 3, 4]
age  = [8, 7, 2, 3, 8, 3, 7]
id_num = np.array(list(range(1, 8))) 

index_num = np.lexsort((-id_num, age, weight))
print(names[index_num])

备注:降序排列可以在数组前加-负号,但是要将数组转换成ndarray数组才能进行负号运算,普通列表则不能进行此运算。

结果:

['C' 'F' 'G' 'B' 'D' 'A' 'E']

复数数组排序sort_complex

按照实部的升序排列,对于实部相同的元素,参考虚部的升序,直接返回排序后的结果数组。

  • 语法
numpy.sort_complex(复数数组)
  • 例子

代码:

import numpy as np

num = np.array([2 + 3j, 1 + 2j, 5 + 1j,
                8 - 2j, 8 + 1j, 2 + 1j])

sorted_num = np.sort_complex(num)
print(sorted_num)

结果:

[ 1.+2.j  2.+1.j  2.+3.j  5.+1.j  8.-2.j  8.+1.j]

插入排序searchsorted

若需要向有序数组中插入元素,使数组依然有序,numpy提供了searchsorted方法,返回待插入元素的可插入位置数组。

  • 语法
indices = numpy.searchsorted(有序序列, 待插序列)
  • 例子

代码:

import numpy as np

a = np.array([1, 2, 4, 5, 7])
b = np.array([3, 6])

c = np.searchsorted(a, b)
print(c)
d = np.insert(a, c, b)
print(d)

备注:numpy提供的insert方法,可向原数组的指定位置插入元素。比如,A为原数组,B为索引数组,C为待插入元素数组。 insert(A, B, C)为向A的B位置插入C数据。

结果:

[2 4]
[1 2 3 4 5 6 7]
发布了141 篇原创文章 · 获赞 24 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/m0_37422217/article/details/105206075