import numpy as np
# 查看版本
np.__version__
使用np的函数
#一维
test = np.array([1,2,3,4,5])
print(test)
# 多维度
test1 = np.array([[1,2,3],[4,5,6]])
(test1)
np.ones([3,3])
# array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
np.ones([3,4], dtype=int)
np.full([3,3], 3.1)
#对角矩阵
np.eye(4)
np.eye(4,4,2)
# 等差数列
np.linspace(0,10,5)
np.arange(0,10,2)
#随机数组
np.random.randint(0,10,5)
np.random.randn(10)
#ipython notebook 快捷键 b向下创建一行,dd删除行
# 随机的种子,有了种子,每次都一样
np.random.seed(100)
np.random.random(10)
ndarray的属性
ndim:维度 shape:形状(各个维度的长度) size:总长度 dtype:元素类型
np.random.seed(0)
#10:随机从0-9之间产生的int类型的值,
#3:代表产生3个矩阵
#4:代表每个矩阵的行数
#5:代表每个矩阵的列数
x = np.random.randint(10,size=([3,4,5]))
x
ndarray的基本操作
索引
np.random.seed(1)
x = np.random.randint(10,size=[3,4,5])
x[2,0,0]
切片
np.random.seed(0)
x = np.random.randint(100,size=(10,4))
x[7:10]
变形
# 使用reshape函数,参数是一个tuple
x = np.arange(0,16).reshape(4,4)
x
联级
np.concatenate()
x = np.array([1,2,3])
y = np.array([1,5,6,7,3,20])
z = np.concatenate([x,y])
z
x = np.array([[1,2,3],[4,5,6]])
x
x.shape
p = np.concatenate([x,x])
p
axis
x = np.array([[[1,2,3],[2,2,3],[3,3,3]],[[4,4,4],[5,5,5],[6,6,6]]])
x.shape
w = np.concatenate([x,x], axis=1)
w.shape
水平联级与垂直联级
x = np.array([[1,1],[2,2],[3,3]])
y = np.array([1,2,3])
print(np.hstack(x))
print(np.vstack(y))
切分
x = np.arange(1,10)
x
x1,x2,x3 = np.split(x,[3,5])
print(x1,x2,x3)
x = np.arange(16).reshape(4,4)
x
# 水平切分,将水平方向的数据切分
print(np.hsplit(x,[2,3,1]))
# 垂直切分,将垂直方向的数据切分
print(np.vsplit(x,[2,3]))