1 求和函数 sum()
求积函数product()
加权平均数 average()
var()求方差
mean()求期望
std()求标准差
说明:在sum()函数中,也可以对列表元祖等与数组类似的序列求和。当数组多维度时,他计算的时所有元素的和。如果指定维度参数axis,则求和沿着指定轴进行。二位数组来说,如果axis=0,则数组沿着第第0轴求和,即对每一列求和,得到一个行矩阵。如果axis = 1则表示沿着第1轴求和,即为对每一行求和。
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np from numpy import random as nr x = nr.randint(1,10,(2,3)) print x print np.sum(x) print np.sum(x,axis = 0) print np.sum(x,axis = 1)
[[8 2 7] [3 2 4]] 26 [11 4 11] [17 9] (Pdb)
std和var分别计算样本的标准差和方差,方差有两种含义:偏方差和无偏方差,具体含义在该来论中定义的。var函数有一个参数ddof,当ddof为0时,计算样本方差,当ddof为1时,计算样本无偏方差,默认值为0.
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np from numpy import random as nr #生成正态分布样本 a = nr.normal(0,2.0,size = (10000,10)) # 计算有偏方差 v1 = np.var(a,axis = 1) #计算无偏方差 v2 = np.var(a,axis = 1,ddof = 1) print v1.mean() print v2.mean()
3.60979905485 4.01088783873 (Pdb)
可以看到有偏方差的期望值比真实方差要小
2 min(),max()最小值和最大值,同样可以指定axis参数
minimum(),maximum() 二元最小值与二元最大值
ptp() 最大值与最小值的差值
argmin()与argmax() 最小值下标和最大值下标
sort() 数组排序
argsort() 计算数组排序的下标
lexsort() 多列排序
partition() 快速计算前k位
argpatiton() 前k位下标
median() 中位数
percentile() 百分位数
searchsorted() 二分查找
# -*- coding: utf-8 -*-"""Spyder Editor This is a temporary script file."""import numpy as npfrom numpy import random as nr x = nr.randint(1,10,size = 10)print xmax_pos = np.argmax(x)min_pos = np.argmin(x)# 输出最大值和最小值的下标print max_pos,min_posprint # 对数组排序x = nr.randint(1,30,size = (3,4))print xprint # sort中默认的axis为-1,即为对着最终轴进行排序print np.sort(x)print #指定对0轴排序,即为每一列排序print np.sort(x, axis = 0)print # 设置axis为None,此时他将得到平坦后排序的新数组print np.sort(x, axis = None)print # 使用argsort()返回数组排序后下标#按照0轴排序print np.argsort(x,axis = 0)print #按照1轴排序print np.argsort(x, axis = 1)
下面为输出结果:
[1 9 7 1 6 9 5 7 1 4]1 0 [[ 8 2 25 26] [ 5 16 25 9] [19 28 18 11]] [[ 2 8 25 26] [ 5 9 16 25] [11 18 19 28]] [[ 5 2 18 9] [ 8 16 25 11] [19 28 25 26]] [ 2 5 8 9 11 16 18 19 25 25 26 28] [[1 0 2 1] [0 1 0 2] [2 2 1 0]] [[1 0 2 3] [0 3 1 2] [3 2 0 1]](Pdb)
legsortd的参数是一个形状为(k,N)的数组,或者包含k个长度为N的数组序列。legsort反回排序下标,需要注意的时,她时按照数组中最后的行为排序的主键。
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np from numpy import random as nr names = ["LiMing","LiuXiang","Mike","XiaoMing","KangKang"] ages = [23,12,34,22,14] #ages为当前最后一行,以ages为主键 idx = np.lexsort([names,ages]) sorted_data = np.array(zip(names,ages)) print sorted_data print #二维数组排序默认以最后一行为主键 x = nr.randint(1,100,size=(4,5)) print x print idx = np.lexsort(x) print x[:,idx]
[[‘LiMing‘ ‘23‘] [‘LiuXiang‘ ‘12‘] [‘Mike‘ ‘34‘] [‘XiaoMing‘ ‘22‘] [‘KangKang‘ ‘14‘]] [[ 7 12 11 51 32] [88 9 46 93 23] [35 26 96 83 63] [94 43 17 26 11]] [[32 11 51 12 7] [23 46 93 9 88] [63 96 83 26 35] [11 17 26 43 94]] (Pdb)
时间: 2024-10-23 19:13:30