Numpy 学习
1. Numpy 的属性
- ndim: 维度
- shape: 行数和列数
- size: 元素个数
2. 用列表转为矩阵
>>> import numpy as np
>>> a = np.array([[2, 3, 4], [3, 4, 6]])
>>> print(a)
"""
[[2 3 4]
[3 4 6]]
"""
# 了解 numpy 的属性
>>> print(a.size)
6
>>> print(a.shape)
(2, 3)
>>> print(a.ndim)
2
>>>
3. 关键字
- array: 创建数组
- dtype: 指定数据类型
- zeros: 创建数据全为0
- ones: 创建数据全为1
- empty: 创建数据接近0
- arrange: 按指定范围创建数据
- linspace: 创建线段
4. 了解 npmpy 关键字
指定数据类型 dtype
>>> a = np.array([23, 34, 53])
>>> print(a.dtype)
int64 # 默认
>>> a = np.array([4, 34, 38], dtype=np.int)
>>> print(a.dtype)
int64
>>> a = np.array([4, 34, 38], dtype=np.int32)
>>> print(a.dtype)
int32
>>> a = np.array([4, 34, 38], dtype=np.float)
>>> print(a.dtype)
float64
>>> a = np.array([4, 34, 38], dtype=np.float32)
>>> print(a.dtype)
float32
>>>
创建特定数据
# 创建 2 行 3 列全 0 数组
>>> a = np.zeros((2, 3))
"""
[[ 0. 0. 0.]
[ 0. 0. 0.]]
"""
# 创建 2 行 3 列全 1 数组
>>> a = np.ones((2, 3))
"""
[[ 1. 1. 1.]
[ 1. 1. 1.]]
"""
# 创建全 1 数组, 并指定数据类型
>>> a = np.ones((2, 4), dtype=np.int)
"""
[[1 1 1 1]
[1 1 1 1]]
"""
# 创建全空数组
>>> a = np.empty((3, 3))
"""
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
"""
# 用 `arange` 创建连续数组: 从 10 到 30, 3 步长
>>> a = np.arange(10, 30, 3)
"""
[10 13 16 19 22 25 28]
"""
5. Shape
改变数组形状 (reshape)
>>> a = np.arange(12)
"""
[ 0 1 2 3 4 5 6 7 8 9 10 11]
"""
>>> a.reshape((3, 4))
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
线段型数据 (linspace)
# 从 1 开始到 10 结束, 分 20 个数据
>>> a = np.linspace(1, 10, 20)
"""
[ 1. 1.47368421 1.94736842 2.42105263 2.89473684
3.36842105 3.84210526 4.31578947 4.78947368 5.26315789
5.73684211 6.21052632 6.68421053 7.15789474 7.63157895
8.10526316 8.57894737 9.05263158 9.52631579 10. ]
"""
# reshape
>>> a = np.linspace(1, 10, 20).reshape((5, 4))
"""
[[ 1. 1.47368421 1.94736842 2.42105263]
[ 2.89473684 3.36842105 3.84210526 4.31578947]
[ 4.78947368 5.26315789 5.73684211 6.21052632]
[ 6.68421053 7.15789474 7.63157895 8.10526316]
[ 8.57894737 9.05263158 9.52631579 10. ]]
"""