numpy基础属性方法随机整理(10):间接联合排序函数np.lexsort和复数直接排序函数np.sort_complex

间接联合排序函数:np.lexsort((scores, ages))
复数直接排序函数:np.sort_complex(c).real

获取array数组的下标:np.where()[0]
通过下标数组返回数组中的元素集:np.take()
注:np.where()的return: tuple((arr_indices, arr_dtype), )

np.where(namesComplexSorted == 'Kity')
    返回值:len==1tuple: (array([1], dtype=int64),)   tuple的元素tuple[0]==(arr_indices, arr_dtype)
    需要处理后才能传入list中用于后续使用 : val_return[0][0]
np.take(ages, np.where(ages == v))
    参数:(数组a, 下标数组)
    返回值:数组a中由下标数组所表示的a数组中的元素集合
1)def take(a, indices, axis=None, out=None, mode='raise'):
    Take elements from an array along an axis.
2)Help on built-in function where in module numpy.core.multiarray:    
where(...)
    where(condition, [x, y])
    Return elements, either from `x` or `y`, depending on `condition`.

code:

# -*- coding: utf-8 -*-
'''

'''

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))] # 间接排序(通过a,b等对c排序; 直接排序是通过a对a排序)
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),)



'''
Help on built-in function lexsort in module numpy.core.multiarray:

lexsort(...)
    lexsort(keys, axis=-1)

    Perform an indirect sort using a sequence of keys.

    Given multiple sorting keys, which can be interpreted as columns in a
    spreadsheet, lexsort returns an array of integer indices that describes
    the sort order by multiple columns. The last key in the sequence is used
    for the primary sort order, the second-to-last key for the secondary sort
    order, and so on. The keys argument must be a sequence of objects that
    can be converted to arrays of the same shape. If a 2D array is provided
    for the keys argument, it's rows are interpreted as the sorting keys and
    sorting is according to the last row, second last row etc.

    Parameters
    ----------
    keys : (k, N) array or tuple containing k (N,)-shaped sequences
        The `k` different "columns" to be sorted.  The last column (or row if
        `keys` is a 2D array) is the primary sort key.
    axis : int, optional
        Axis to be indirectly sorted.  By default, sort over the last axis.

    Returns
    -------
    indices : (N,) ndarray of ints
        Array of indices that sort the keys along the specified axis.
'''

'''
def sort_complex(a):

    Sort a complex array using the real part first, then the imaginary part.
'''

猜你喜欢

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