import numpy as np
1.arange对array赋值,arange函数类似range
a = np.arange(12).reshape(4,3)
a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
查看数组中元素的类型a.dtype
dtype('int32')
a.dtype.name
'int32'
查看数组维度a.ndim
2
查看数组每个维度的长度a.shape
(4,3)
查看数组元素总数a.size
15
复制a的结构,所有元素值为1
b = np.ones_like(a)
b
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
数组运算
c = a-b
c
array([[-1, 0, 1],
[ 2, 3, 4],
[ 5, 6, 7],
[ 8, 9, 10]])
d = c*1.5
d
array([[ -1.5, 0. , 1.5],
[ 3. , 4.5, 6. ],
[ 7.5, 9. , 10.5],
[ 12. , 13.5, 15. ]])
d<2
array([[ True, True, True],
[False, False, False],
[False, False, False],
[False, False, False]], dtype=bool)
创建单位矩阵,identity
e = np.identity(3,dtype = 'int64')
e
array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]], dtype=int64)
f = np.eye(3,4)
f
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.]])
矩阵乘法np.dot(f,a)
array([[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]])