NumPy#
导入工具库#
Numpy是Python数据科学计算的核心库,提供了高性能的多维数组对象及处理数组的工具。
使用以下语句导入Numpy库:
import numpy as np
Numpy数组#
1维数组
2维数组【axis 1 axis 0】
3维数组【axis 2 axis 1 axis 0】
创建数组#
初始化#
a = np.array([1, 2, 3])
b = np.array([(1.5, 2, 3), (4, 5, 6)], dtype=float)
c = np.array([[(1.5, 2, 3), (4, 5, 6)], [(3, 2, 1), (4, 5, 6)]], dtype=float)
特殊数组#
np.zeros((3, 4)) # 创建值为 0 数组
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
np.ones((2, 3, 4), dtype=np.int16) # 创建值为 1 数组
array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]], dtype=int16)
d = np.arange(10, 25, 5) # 创建均匀间隔的数组(步进值)
np.linspace(0, 2, 9) # 创建均匀间隔的数组(样本数)
array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
e = np.full((2, 2), 7) # 创建常数数组
f = np.eye(2) # 创建 2 x 2 单位矩阵
np.random.random((2, 2)) # 创建随机值的数组
array([[0.52967042, 0.82018357],
[0.08207694, 0.65795456]])
np.empty((3, 2)) # 创建空数组
array([[6.9259745e-310, 6.9259745e-310],
[0.0000000e+000, 0.0000000e+000],
[0.0000000e+000, 0.0000000e+000]])
输入/输出#
保存与载入磁盘上的文件#
np.save("../_tmp/np_save", a)
np.savez('../_tmp/np_savez.npz', a, b)
np.load('../_tmp/np_save.npy')
array([1, 2, 3])
np.savetxt("../_tmp/np_savetxt.txt", a, delimiter=" ")
保存与载入文本文件#
np.loadtxt("../_tmp/np_savetxt.txt")
array([1., 2., 3.])
np.genfromtxt("../_tmp/np_savetxt.txt", delimiter=" ")
array([1., 2., 3.])
数据类型#
有以下的一些数据类型
np.int64 # 带符号的 64 位整数
numpy.int64
np.float32 # 标准双精度浮点数
numpy.float32
np.complex128 # 显示为 128 位浮点数的复数
numpy.complex128
np.bool_ # 布尔值:True 值和 False 值
numpy.bool
object # Python 对象
object
np.bytes_
numpy.bytes_
np.str_
numpy.str_
数组信息#
查看数组的基本信息
a.shape # 数组形状,几行几列
(3,)
len(a) # 数组长度
3
b.ndim # 几维数组
2
e.size # 数组有多少元素
4
b.dtype # 数据类型
dtype('float64')
b.dtype.name # 数据类型的名字
'float64'
b.astype(int) # 数据类型转换
array([[1, 2, 3],
[4, 5, 6]])
数组计算#
算数运算#
g = a - b # 减法
g
array([[-0.5, 0. , 0. ],
[-3. , -3. , -3. ]])
np.subtract(a, b) # 减法
array([[-0.5, 0. , 0. ],
[-3. , -3. , -3. ]])
b + a # 加法
array([[2.5, 4. , 6. ],
[5. , 7. , 9. ]])
np.add(b, a) # 加法
array([[2.5, 4. , 6. ],
[5. , 7. , 9. ]])
a / b # 除法
array([[0.66666667, 1. , 1. ],
[0.25 , 0.4 , 0.5 ]])
np.divide(a, b) # 除法
array([[0.66666667, 1. , 1. ],
[0.25 , 0.4 , 0.5 ]])
a * b # 乘法
array([[ 1.5, 4. , 9. ],
[ 4. , 10. , 18. ]])
np.multiply(a, b) # 乘法
array([[ 1.5, 4. , 9. ],
[ 4. , 10. , 18. ]])
np.exp(b) # 幂
array([[ 4.48168907, 7.3890561 , 20.08553692],
[ 54.59815003, 148.4131591 , 403.42879349]])
np.sqrt(b) # 平方根
array([[1.22474487, 1.41421356, 1.73205081],
[2. , 2.23606798, 2.44948974]])
np.sin(a) # 正弦
array([0.84147098, 0.90929743, 0.14112001])
np.cos(b) # 余弦
array([[ 0.0707372 , -0.41614684, -0.9899925 ],
[-0.65364362, 0.28366219, 0.96017029]])
np.log(a) # 自然对数
array([0. , 0.69314718, 1.09861229])
e.dot(f) # 点积
array([[7., 7.],
[7., 7.]])
比较#
a == b # 对比值
array([[False, True, True],
[False, False, False]])
a < 2 # 对比值
array([ True, False, False])
np.array_equal(a, b) # 对比数组
False
聚合函数#
a.sum() # 数组汇总
np.int64(6)
a.min() # 数组最小值
np.int64(1)
b.max(axis=0) # 数组最大值,按行
array([4., 5., 6.])
b.cumsum(axis=1) # 数组元素的累加值
array([[ 1.5, 3.5, 6.5],
[ 4. , 9. , 15. ]])
a.mean() # 平均数
np.float64(2.0)
np.median(b) # 中位数
np.float64(3.5)
np.corrcoef(a, b) # 相关系数
array([[1. , 0.98198051, 1. ],
[0.98198051, 1. , 0.98198051],
[1. , 0.98198051, 1. ]])
np.std(b) # 标准差
np.float64(1.5920810978785667)
数组复制#
可以通过 copy 复制数组
h = a.view() # 使用同一数据创建数组视图
np.copy(a) # 创建数组的副本
array([1, 2, 3])
h = a.copy() # 创建数组的深度拷贝
数组排序#
通过sort进行数组排序
a.sort() # 数组排序
c.sort(axis=0) # 以轴为依据对数组排序
子集、切片、索引#
子集#
a[2] # 选择索引 2 对应的值
np.int64(3)
b[1, 2] # 选择行列 index 为 1 和 2 位置对应的值(等同于 b[1][2])
np.float64(6.0)
切片#
a[0:2] # 选择索引为 0 与 1 对应的值
array([1, 2])
b[0:2, 1] # 选择第 1 列中第 0 行、第 1 行的值
array([2., 5.])
b[:1] # 选择第 0 行的所有值(等同于 b[0:1, :1])
array([[1.5, 2. , 3. ]])
c[1, ...] # 等同于 [1, :, :]
array([[3., 2., 3.],
[4., 5., 6.]])
a[::-1] # 反转数组 a
array([3, 2, 1])
a[a < 2] # 选择数组 a 中所有小于 2 的值
array([1])
b[[1, 0, 1, 0], [0, 1, 2, 0]] # 选择 (1, 0), (0, 1), (1, 2) 和 (0, 0) 所对应的值
array([4. , 2. , 6. , 1.5])
b[[1, 0, 1, 0]][:, [0, 1, 2, 0]] # 选择矩阵的行列子集
array([[4. , 5. , 6. , 4. ],
[1.5, 2. , 3. , 1.5],
[4. , 5. , 6. , 4. ],
[1.5, 2. , 3. , 1.5]])
数组操作#
转置数组#
i = np.transpose(b) # 转置数组
i.T # 转置数组
array([[1.5, 2. , 3. ],
[4. , 5. , 6. ]])
改变数组形状#
b.ravel() # 拉平数组
array([1.5, 2. , 3. , 4. , 5. , 6. ])
g.reshape(3, -2) # 改变数组形状,但不改变数据
array([[-0.5, 0. ],
[ 0. , -3. ],
[-3. , -3. ]])
添加或删除值#
h.resize((2, 6)) # 返回形状为 (2, 6) 的新数组
np.append(h, g) # 追加数据
array([ 1. , 2. , 3. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ,
0. , -0.5, 0. , 0. , -3. , -3. , -3. ])
np.insert(a, 1, 5) # 插入数据
array([1, 5, 2, 3])
np.delete(a, [1]) # 删除数据
array([1, 3])
合并数组#
np.concatenate((a, d), axis=0) # 拼接数组
array([ 1, 2, 3, 10, 15, 20])
np.vstack((a, b)) # 纵向以行的维度堆叠数组
array([[1. , 2. , 3. ],
[1.5, 2. , 3. ],
[4. , 5. , 6. ]])
np.r_[e, f] # 纵向以行的维度堆叠数组
array([[7., 7.],
[7., 7.],
[1., 0.],
[0., 1.]])
np.hstack((e, f)) # 横向以列的维度堆叠数组
array([[7., 7., 1., 0.],
[7., 7., 0., 1.]])
np.column_stack((a, d)) # 以列的维度创建堆叠数组
array([[ 1, 10],
[ 2, 15],
[ 3, 20]])
np.c_[a, d] # 以列的维度创建堆叠数组
array([[ 1, 10],
[ 2, 15],
[ 3, 20]])
分割数组#
np.hsplit(a, 3) # 纵向分割数组为 3 等份
[array([1]), array([2]), array([3])]
np.vsplit(c, 2) # 横向分割数组为 2 等份
[array([[[1.5, 2. , 1. ],
[4. , 5. , 6. ]]]),
array([[[3., 2., 3.],
[4., 5., 6.]]])]
调用帮助#
通过info函数调用帮助信息
np.info(np.ndarray.dtype)
Data-type of the array's elements.
.. warning::
Setting ``arr.dtype`` is discouraged and may be deprecated in the
future. Setting will replace the ``dtype`` without modifying the
memory (see also `ndarray.view` and `ndarray.astype`).
Parameters
----------
None
Returns
-------
d : numpy dtype object
See Also
--------
ndarray.astype : Cast the values contained in the array to a new data-type.
ndarray.view : Create a view of the same data but a different data-type.
numpy.dtype
Examples
--------
>>> x
array([[0, 1],
[2, 3]])
>>> x.dtype
dtype('int32')
>>> type(x.dtype)
<type 'numpy.dtype'>