使用numpy.random模块来生成随机数组
1、np.random.rand 用于生成[0.0, 1.0)之间的随机浮点数, 当没有参数时,返回一个随机浮点数,当有一个参数时,返回该参数长度大小的一维随机浮点数数组,参数建议是整数型,因为未来版本的numpy可能不支持非整形参数。
import numpy as np
>>> np.random.rand(10)
array([ 0.56911206, 0.99777291, 0.18943144, 0.19387287, 0.75090637,
0.18692814, 0.69804514, 0.48808425, 0.79440667, 0.66959075])
2、np.random.randn该函数返回一个样本,具有标准正态分布。
>>> np.random.randn(10)
array([-1.6765704 , 0.66361856, 0.04029481, 1.19965741, -0.57514593,
-0.79603968, 1.52261545, -2.17401814, 0.86671727, -1.17945975])
3、np.random.randint(low[, high, size]) 返回随机的整数,位于半开区间 [low, high)。
>>> np.random.randint(10,size=10)
array([4, 1, 4, 3, 8, 2, 8, 5, 8, 9])
4、random_integers(low[, high, size]) 返回随机的整数,位于闭区间 [low, high]。
>>> np.random.random_integers(5)
4
5、np.random.shuffle(x) 类似洗牌,打乱顺序;np.random.permutation(x)返回一个随机排列
np.random.permutation与np.random.shuffle有两处不同:
- 如果传给permutation一个矩阵,它会返回一个洗牌后的矩阵副本;而shuffle只是对一个矩阵进行洗牌,无返回值。
- 如果传入一个整数,它会返回一个洗牌后的arange.
举例:
import pandas as pd import numpy as np valu=[] statu=[] sd=np.array([[1,8],[3,10],[2,2]]) dates=pd.date_range('20130101',periods=3) ss=pd.DataFrame(sd,columns=list('AB')) tt=np.random.permutation(len(ss)) X=ss.iloc[tt] for i in range(len(ss)): valu.append(ss.iloc[i].tolist()) if i<=2: sums=ss.iloc[i].sum() if sums>10: s=1 else: s=0 statu.append(s) print valu print statu status=pd.DataFrame(statu,columns=['a']) print status print X
输出:
[[1, 8], [3, 10], [2, 2]] [0, 1, 0] a 0 0 1 1 2 0 A B 1 3 10 0 1 8 2 2 2