numpy基础属性方法随机整理(9):专用函数-- np.lexsort() / np.sort_complex两种方法实现间接联合排序

间接联合排序: 间接获取排序样本的下标
原始数列:8 2 3 1 7 4 6 5 9
直接排序:1 2 3 4 5 6 7 8 9
间接排序:3 1 2 5 7 6 4 0 8 (原始序列元素的下标)
姓名:张三 李四 王五 赵六 陈七
成绩:90 70 50 80 60
下标:0 1 2 3 4
成绩升序对应的下标:2 4 1 3 0
年龄:20 30 30 20 40 (有相同值,对年龄排序时参考成绩进行联合排序)
下标:
联合排序对应的下标:3 0 2 1 4(年龄升序)

函数语法:

   numpy.lexsort((参考序列,待排序列)) ---> return:索引序列
   np.sort_complex(复数数组) ---> 按实部的升序排列,实部相同的参考虚部的升序排列
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 16:36:45 2018

@author: Administrator
"""

'''
np.where(namesComplexSorted == 'Kity')
    返回值:(array([1], dtype=int64),)   tuple和list复合的
    需要处理后才能传入list中用于后续使用 : val_return[0][0]
np.take(ages, np.where(ages == v))
    参数:(数组a, 下标数组)
    返回值:数组a中由下标数组所表示的a数组中的元素集合
'''

import numpy as np

names = np.array(['Tom','Mike','Jue','Kity','scote'])
scores = np.array([90., 70., 68., 80., 76.])
ages = np.array([29, 23, 20, 22, 27])               # [29 23 20 22 27]

# 联合排序方法1:返回下标index
index_lexsorted = np.lexsort((scores, ages))        # [2 3 1 4 0]
print(index_lexsorted)

names_lexsorted = names[np.lexsort((scores, ages))]
print(names_lexsorted)      # ['Jue' 'Kity' 'Mike' 'scote' 'Tom']

print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')

# 联合排序方法2: 巧用复数进行联合排序
c = ages + scores * 1j                              # j要用 1j 表示
d = np.sort_complex(c).real                         # float:[20. 22. 23. 27. 29.] <class 'numpy.ndarray'>
d = d.astype('int64')                               # int:[20 22 23 27 29] <class 'numpy.ndarray'>

index_names = []
for i, v in enumerate(d):
    print(np.where(ages ==v)[0][0], np.take(ages, np.where(ages == v))[0][0])
    index_names.append(np.where(ages ==v)[0][0])    # 按照d的元素顺序依次对比,取出ages的下标

namesComplexSorted = names[index_names]
print(namesComplexSorted)                           # ['Jue' 'Kity' 'Mike' 'scote' 'Tom']
print(np.where(namesComplexSorted == 'Kity')[0][0]) # (array([1], dtype=int64),)

猜你喜欢

转载自blog.csdn.net/weixin_40040404/article/details/81252812