numpy学习笔记(2)
资料来源:Python知识手册,csdn
numpy.random函数
- random.rand函数
给定维度生成[0,1)间的ndarray
>>> import numpy as np
>>> np.random.rand(4,2)
array([[0.45688739, 0.26886546],
[0.69148437, 0.61480271],
[0.37722378, 0.305412 ],
[0.79430114, 0.75512251]])
>>> np.random.rand(5,2,3)
array([[[0.75038532, 0.83388829, 0.62408375],
[0.46336842, 0.34015173, 0.53301729]],
[[0.26157672, 0.65139399, 0.47581856],
[0.61984685, 0.70623299, 0.28065171]],
[[0.19054782, 0.59329701, 0.05462034],
[0.26053959, 0.01264219, 0.40373975]],
[[0.32033322, 0.71297706, 0.70064409],
[0.98279322, 0.1686095 , 0.46542026]],
[[0.34178765, 0.31608295, 0.71511896],
[0.01467071, 0.5376934 , 0.20550826]]])
- random.randn函数
返回一组给定维度的具有正态分布的ndarray - random.randint(low, high=None, size=None, dtype=‘l’)函数
返回随机整数, low为下限,high为上限,size是维度,dtype是数据类型 - 生成随即小数的四种方法
random.random_sample
random.random
random.ranf
random.sample - random.choice(a, size=None, replace=True, p=None)函数
a表示数据的取值范围是0到a
size对应数组的维度
p是出现的概率
>>> import numpy as np
>>> a = np.random.choice(7,3)
>>> a
array([4, 2, 1])
- Meshgrid函数
若向量x为一行m列,y为一行n列。经过mesgrid函数变换之后,产生了对应的X,Y的维度是(n*m)。也就是说,最终结果都是(n·m),依据x,y的长度不同,复制方式也会不同。
>>> m,n = (5,3)
>>> x = np.linspace(0,1,m)
>>> y = np.linspace(0,1,n)
>>> X,Y = np.meshgrid(x,y)
>>> X
array([[0. , 0.25, 0.5 , 0.75, 1. ],
[0. , 0.25, 0.5 , 0.75, 1. ],
[0. , 0.25, 0.5 , 0.75, 1. ]])
>>> Y
array([[0. , 0. , 0. , 0. , 0. ],
[0.5, 0.5, 0.5, 0.5, 0.5],
[1. , 1. , 1. , 1. , 1. ]])
>>> X.shape
(3, 5)
补充:
flat函数:flat返回的是一个迭代器,可以用for访问数组每一个元素,不可打印。
for i in X.flat:
print(i)
0.0
0.25
0.5
0.75
1.0
0.0
0.25
0.5
0.75
1.0
0.0
0.25
0.5
0.75
1.0
zip函数:将相同大小的对象对应位置元素打包成元组
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
————————————————
版权声明:本文为优快云博主「CodingAndCoCoding」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Wangtuo1115/article/details/106460441