python科学计算_numpy_常规函数与排序 标签: numpypython排序

来源:互联网 发布:高分子材料与工程知乎 编辑:程序博客网 时间:2024/05/16 00:53

转自:

http://blog.csdn.net/zine_123/article/details/51746567

常用统计函数:

求和:sum()、均值:mean()、标准差:std()、方差:var()、最小值:min()、最大值:max()、最大值与最小值之差:ptp()、最大值的下标:argmax()、最小值的下标:argmin()、中值:median()

上述函数都可以指定axis,来沿着某一轴操作;除了mean()函数求均值,还可以使用average(),并且可以指定weights参数来指定权值,计算加权平均;argmax()和argmin()如果不指定axis参数,则返回平坦化后的下标;

排序函数:sort()、argsort();数组的sort()方法会对数组本身进行改变,而sort()函数则不会;sort默认axis=-1,即沿着最后一个轴进行排序;sort()函数返回一个新的排序后的数组而argsort()则返回排序后的下标数组,如:

import numpy as np
a = np.random.randint(0,10,size=(4,5))

array([[8, 2, 0, 3, 7],
[7, 0, 2, 7, 4],
[1, 8, 1, 1, 2],
[4, 6, 2, 1, 4]])

a.sort() #此时a数组会改变为排序后的数组;

a1 = np.sort(a)  #此时a数组不变,得到的a1数组为:

array([[0, 2, 3, 7, 8],
[0, 2, 4, 7, 7],
[1, 1, 1, 2, 8],
[1, 2, 4, 4, 6]])

# 即沿着-1轴排序后的结果 对每行按列排序 

>>> a2 = np.sort(a,axis = 0)
>>> a2
array([[3, 0, 2, 6, 2],
       [4, 3, 3, 7, 2],
       [5, 6, 5, 7, 2],
       [7, 8, 9, 8, 4]])

# 即沿着0轴排序后的结果 对每列按行排序 

idx = np.argsort(a)

idx

array([[2, 1, 3, 4, 0],
[1, 2, 4, 0, 3],
[0, 2, 3, 4, 1],
[3, 2, 0, 4, 1]])

此时,虽然idx.shape = (4,5),但是并不能直接使用a[idx]得到排序后的数组,因为idx是数组,所以numpy会在后面补:,等效于:a[idx,:],idx数组中的每个值访问a数组的0轴,当idx中的值超过a的0轴长度之后就会产生错误:IndexError: index 4 is out of bounds for axis 0 with size 4;所以使用idx来访问a得到排序后的数组,需要产生0轴的下标,通过np.ogrid对象可以生成:

x,_ = np.ogrid[:a.shape[0],:a.shape[1]]

右边的表达式生成a数组的grid,即各个轴的下标数组,取第一个元素即得到a数组的0轴下标数组:

array([[0],
[1],
[2],
[3]])

通过a[x,idx]可以正确访问到排序后的数组

0 0