import numpy as np
arr=np.array([1,2,3,4,5])
arr
array([1, 2, 3, 4, 5])
arr.dtype
dtype('int32')
np.zeros(10)
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
np.zeros((3,4))
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
注意empty并非返回空值,很多情况下是随机的,文档如下
empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the array, and should be used with caution
np.empty((2,3,3))
array([[[ 6.23042070e-307, 4.67296746e-307, 1.69121096e-306],
[ 6.23062102e-307, 8.45593934e-307, 7.56593017e-307],
[ 1.11261027e-306, 1.11261502e-306, 1.42410839e-306]],
[[ 7.56597770e-307, 6.23059726e-307, 1.42419530e-306],
[ 1.11261027e-306, 1.60218491e-306, 1.69122046e-306],
[ 1.42419802e-306, 2.22522596e-306, 2.56765117e-312]]])
np.ones((2,3))
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
#n*n单位矩阵
np.eye(3)
np.identity(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
索引和切片
数组切片是原始数据的视图,视图上的任何修改都会反映到源数据上,这点不同于列表
arr
array([1, 2, 3, 4, 5])
#切片从0 开始,包含左不包含右
arr[1:3]
array([2, 3])
#数据切片是原始数据的视图,视图上的任何修改都会反映到源数据上;
arr[3:5]=10
arr
array([ 1, 2, 3, 10, 10])
arr2d=np.array([[1,2,3],[4,5,6],[7,8,9]])
arr2d
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
#切片是沿着某个轴向选取元素
arr2d[1]
array([4, 5, 6])
arr2d[1,2]
6
花式索引
花式索引是将数据复制到新数组
arr=np.arange(32).reshape((8,4))
arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]])
arr[[4,3,5,6],[3,2,1,0]]
array([19, 14, 21, 24])