numpy基本操作(一)

<title>numpy基本操作(一)</title> <body> <div tabindex="-1" id="notebook" class="border-box-sizing"> <div class="container" id="notebook-container">
In [4]:
import numpy as np

In [3]:
#添加一个数组,一维的,全部是0
np.zeros(10)

Out[3]:

array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In [5]:
#添加一个数组,二维维的(3行五5),全部是0
np.zeros((3,5))

Out[5]:

array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])
In [8]:
#添加一个数组,二维,全是同一个数
np.full(shape=(3,5),fill_value=666.0)

Out[8]:

array([[666., 666., 666., 666., 666.],
       [666., 666., 666., 666., 666.],
       [666., 666., 666., 666., 666.]])

arange-序列数组

In [9]:
#python的列表生成式

In [10]:
[i for i in range(10)]

Out[10]:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]:
#numpy的序列数组(效果同python,但numpy可生成多维的)

In [12]:
np.arange(10)

Out[12]:

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

linspace-等步长数组

In [14]:
#生成一个0到20之间的10个等长数组,这里可以理解为生成一个等差数列
np.linspace(0,20,10)

Out[14]:

array([ 0.        ,  2.22222222,  4.44444444,  6.66666667,  8.88888889,
       11.11111111, 13.33333333, 15.55555556, 17.77777778, 20.        ])
In [15]:
#这里生成11个等步长的10个数就刚好是整数
np.linspace(0,20,11)

Out[15]:

array([ 0.,  2.,  4.,  6.,  8., 10., 12., 14., 16., 18., 20.])

random-随机数

In [17]:
#生成随机整数与python一致,左闭右开,也就是取不到20
np.random.randint(0,20,size=10)

Out[17]:

array([ 5,  7, 18, 13, 14,  9,  1, 12, 10,  1])
In [19]:
#size这里代表维度,多维度传入元组即可
np.random.randint(10,20,size=(4,4))

Out[19]:

array([[17, 17, 10, 11],
       [18, 14, 12, 19],
       [12, 19, 19, 16],
       [11, 10, 13, 15]])
In [21]:
#seed--指定随机矩阵,再次调用可以回放之前所取的随机数
np.random.seed(888)
np.random.randint(10,20,size=(4,4))

Out[21]:

array([[16, 13, 17, 19],
       [11, 10, 10, 19],
       [13, 10, 16, 13],
       [12, 14, 11, 17]])
In [23]:
#这里再次调用888可以使得两次随机数一致
np.random.seed(888)
np.random.randint(10,20,size=(4,4))

Out[23]:

array([[16, 13, 17, 19],
       [11, 10, 10, 19],
       [13, 10, 16, 13],
       [12, 14, 11, 17]])
In [24]:
#生成一个随机浮点数(会在0和1之间随机取)
np.random.random()

Out[24]:

0.5584303506361035
In [25]:
#生成一个随机浮点数数组
np.random.random(10)

Out[25]:

array([0.91604736, 0.63346045, 0.28325261, 0.36536881, 0.09223386,
       0.37251258, 0.34742278, 0.70517077, 0.64850904, 0.04090877])
In [ ]:
 

In [26]:
# 生成一个符合正态分布的随机浮点数
np.random.normal()

Out[26]:

-0.35108113795432516
In [29]:
#同样也可以生成数组(表示均值为10,方差为100的一系列数组)
np.random.normal(10,100,size=(3,5))

Out[29]:

array([[   5.09004527,  -33.15967702,  -98.87509907, -221.08810587,
        -176.2364195 ],
       [  33.47086736,  -79.55859209,  -44.08345249,  -30.23990608,
          12.31458561],
       [  27.76885058,  -47.33092723,  -23.83921384,    9.73557789,
         154.93033904]])
In [ ]:
 

In [ ]:
 

</div> </div> </div> </body>
posted @ 2019-12-08 22:03  Missv4you  阅读(62)  评论(0)    收藏  举报