numpy数组1 2018-05-22

Numpy 学习笔记

import numpy as np

#列表生成数组
array_list = np.array([1,2,3])

#获取数组的一些属性
array_list.shape

(3,)

array_list.size

3

array_list.dtype

dtype('int64')

#arange 生成数组
#np.arange(start,stop,step)
array_arange = np.arange(0,10,2)
array_arange

array([0, 2, 4, 6, 8])

#linspace 生成树组
#np.linspace(start,stop,num,endpoint=True, retstep=False, dtype=None)
array_linspace = np.linspace(0,10,5)
array_linspace

array([ 0. , 2.5, 5. , 7.5, 10. ])

#logspace 生成数组
#logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
#等比数列,第一个值为base的start次幂,最后一个为base的stop次幂
array_logspace = np.logspace(1,10,5)
array_logspace

array([ 1.00000000e+01, 1.77827941e+03, 3.16227766e+05,
5.62341325e+07, 1.00000000e+10])

x,y = np.mgrid[0:5,0:5]
x

array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])

y

array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])

#指定shape生成数组(0-1)
np.random.rand(3,3,3)

array([[[ 0.04470474, 0.03879152, 0.03275731],
[ 0.98428623, 0.15772776, 0.58899634],
[ 0.84854996, 0.57448251, 0.8146893 ]],
[[ 0.81999136, 0.84497858, 0.32102928],
[ 0.11496481, 0.85454281, 0.98375146],
[ 0.98902028, 0.9543512 , 0.87608918]],
[[ 0.57644803, 0.51756441, 0.65062625],
[ 0.90273673, 0.15177684, 0.34250122],
[ 0.77310945, 0.26566415, 0.47316576]]])

np.random.randn(2,2)

array([[-0.01836103, -1.39107696],
[ 0.26298797, -0.89930235]])

#矩阵对角线元素
np.diag([1,2,3])

array([[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])

x=np.arange(1,10).reshape((3,3))
print(x)
np.diag(x)

[[1 2 3]
[4 5 6]
[7 8 9]]

array([1, 5, 9])

np.diag(x,1)

array([2, 6])

np.diag(x,-1)

array([4, 8])

np.diag(np.diag(x))

array([[1, 0, 0],
[0, 5, 0],
[0, 0, 9]])

#全0矩阵
np.zeros((3,3))

array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])

#全1矩阵
np.ones((3,3))

array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])

#高级索引
a = np.random.randint(1,100,9).reshape((3,3))
a_index = [1,2]
print(a)

[[95 49 67]
[49 36 53]
[92 45 27]]

a[a_index]

array([[49, 36, 53],
[92, 45, 27]])

a = np.array([1,2,3,4,5])
a_mask = np.array([True,False,True,True,False])
a_mask_num = np.array([1,0,1,1,0],dtype=bool)
a

array([1, 2, 3, 4, 5])

a[a_mask]

array([1, 3, 4])

a[a_mask_num]

array([1, 3, 4])

mask = (1 < a ) * (a < 4)
mask

array([False, True, True, False, False], dtype=bool)

a[mask]

array([2, 3])

你可能感兴趣的:(numpy数组1 2018-05-22)