numpy数组排序

from numpy import *
import numpy as np

# numpy数组排序
# 先看一个例子输入姓名和值 输出姓名根据值大小排序
names = array(['spring', 'oko', 'james', 'cisco'])
weights = array([20.8, 3.0, 40.2, 99])
# argsort 反回由小到大的索引array list
index = argsort(weights)
print(names[index])  # 升序
print(names[index[::-1]])  # 降序
# sort 函数不会改变值排序
sort(weights)
print(weights)  # [20.8  3.  40.2 99. ]
# sort方法会改变数组值排序
weights.sort()
print(weights)  # [ 3.  20.8 40.2 99. ]

# 二维数组排序
a = array([
    [.2, .1, .5],
    [.4, .8, .3],
    [.9, .6, .7]
])
display = sort(a)
print(display)
""" 默认沿着最后维度排序
[[0.1 0.2 0.5]
 [0.3 0.4 0.8]
 [0.6 0.7 0.9]]
"""
display = sort(a, axis=0)  # 改变轴 对每一列排序
print(display)

# 提取数组中在指定界限之间的所有值,要求是排序好的数组
data = np.random.rand(100)
data.sort()
bounds = .4, .6
low_index, high_index = searchsorted(data, bounds)  # bounds为元组

result = data[low_index:high_index].copy()
print(result)

猜你喜欢

转载自blog.csdn.net/SpringQAQ/article/details/81269442
今日推荐