numpy的使用1

numpy的使用1,第1张

numpy的使用1 调用
import numpy as np
与列表和普通数组的比较

列表

L =[i for i in range(10)]
L
output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
L[5]="ML"
L
output:[0, 1, 2, 3, 4, 'ML', 6, 7, 8, 9]

列表可以存储任何数据类型,但是代价是速度慢。

数组
数组只能存储指定类型,例如:

arr= array.array('i',[i for i in range(10)])

代表存10个int型的元素
numpy.array
它很快,并且支持向量运算。

nparr = np.array([i for i in range(10)])
nparr[5]
output:5

它可以接受类型兼容,比如int和float就会兼容成float。

np.zeros(10)
生成10个0,默认为浮点型
np.zeros(10,dtype=int)
生成10个整型的0
np.zeros(shape=(3,5),dtype=int)
生成矩阵,类型为int型
output: 
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
np.ones(10)
output:
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
np.full((3,5),666)
output:
array([[666, 666, 666, 666, 666],
       [666, 666, 666, 666, 666],
       [666, 666, 666, 666, 666]])

一般使用full函数时会显式给参数赋值,类似这样:

np.full(fill_value=12,shape=10)

arange
类似于python里的range,不过它的步长支持浮点数

np.arange(0,20,2)
np.arange(0,1,0.2)
output:array([0. , 0.2, 0.4, 0.6, 0.8])

linspace
包含起始点和终止点,第三个参数不是步长,而是要截多少个数‘

np.linspace(10,20,10)
out:array([10.        , 11.11111111, 12.22222222, 13.33333333, 14.44444444,
       15.55555556, 16.66666667, 17.77777778, 18.88888889, 20.        ])

np.random.randint
生成随机整数

np.random.randint(0,10,10)
out:array([9, 0, 8, 3, 7, 2, 1, 3, 5, 5])
np.random.randint(4,8,size=(3,5))
out:
array([[4, 6, 5, 6, 6],
       [6, 5, 6, 4, 5],
       [7, 6, 7, 4, 7]])

随机数种子:给定了随机数种子,生成的随机数就固定了

np.random.seed(666)
np.random.random()

生成0到1之间的随机数

 np.random.normal()

生成符合均值为0,方差为1的随机数

np.random.normal(10,100)

生成均值为10,方差为100的随机数

np.random.normal?询问该函数的使用方法
也可以用help(np.random.normal)

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5479509.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存