代码:
# 类型
# 一维矩阵
a = np.array([2, 23, 4], dtype=np.int)
print(a.dtype)
a = np.array([2, 23, 4], dtype=np.float)
print(a.dtype)
print(a)
# 二维
a = np.array([[1, 2, 3],
[4, 5, 6]])
print(a)
运行结果:
(2, 3, 3)
3
(2, 3, 3)
3
代码:
# 全部为零
a = np.zeros((3, 4))
print(a)
# 全部为一
a = np.ones((3, 4), dtype=np.int16)
print(a)
# 什么都没有
a = np.empty((3, 4))
print(a)
运行结果:
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
代码:
# 有序矩阵
a = np.arange(1, 10, 5) # 步长为5
print("有序矩阵")
print(a)
# 二维
a = np.arange(12).reshape((3, 4))
print(a)
b = np.arange(1, 25, 1).reshape((2, 3, 4))
print(b)
运行结果:
有序矩阵
[1 6]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
代码:
# 线段
a = np.linspace(1, 10, 5) # 生成五部分
print("生成五部分")
print(a)
# 二维
a = np.linspace(1, 10, 6).reshape((2, 3))
print(a)
# 三维
b = np.linspace(1, 24, 24).reshape((2, 3, 4))
print(b)
运行结果:
生成五部分
[ 1. 3.25 5.5 7.75 10. ]
[[ 1. 2.8 4.6]
[ 6.4 8.2 10. ]]
[[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
[[ 13. 14. 15. 16.]
[ 17. 18. 19. 20.]
[ 21. 22. 23. 24.]]]