以下为 numpy 的基本使用
详细的使用手册可以参考 NumPy Documentation
1. numpy 对象的属性
a.shape: the dimensions of the array.
a.ndim: the number of axes (dimensions) of the array.
a.dtype: an object describing the type of the elements in the array.
a.size: the total number of elements of the array.
import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape) # (3, 5)
print(a.ndim) # 2
print(a.dtype) # int32
print(a.size) # 15
print(a.itemsize) # 4
print(type(a)) # <class 'numpy.ndarray'>
2. Array Creation
2.1 np.array
利用 numpy 的 array
函数可以将 list 或 tuple
可以指定数据的类型:
b = np.array([1, 2, 3], dtype=np.float32)
c = np.array([1+2j, 3j, 5], dtype=complex)
默认的浮点数类型为 np.float64
,默认的整型类型为 np.int32
,默认的复数类型为 np.complex28
2.2 sequences
也可以利用现有的函数构造 Array:
np.ones((2, 3))
np.zeros((2, 3))
# create sequences of numbers
np.arange(0, 5, 0.5)
np.linspace(0, 2*np.pi, 10).reshape(2, 5)
2.3 np.random
利用 numpy.random
的函数可以产生随机数:
np.random.rand(2, 3) # [0, 1] 均匀分布 大小为 2 x 3
np.random.randn(2, 3) # [0, 1] 正态分布
np.random.randint(0, 5, (3, 4)) # [0, 5) 均匀分布
3. print Array
多维的元素布局方式如下:
- 最后一维的数据从左至右排列
- 其余维度从上到下排列
如 reshape(2, 3, 4)
将数组变换为 2层 3行 4列的矩阵:
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a)
结果如下:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
4. Basic Operation
4.1 常见算数运算
numpy 数组支持常用的算术运算,结果存储在新的数组中:
import numpy as np
a = np.arange(4).reshape(2, 2)
print(a**2)
print(np.exp(a))
print(2*np.sin(a))
print(np.sqrt(np))
使用 +=
, -=
, *=
会将计算结果覆盖到原始数组中
4.2 multiply
*
会将所有元素按元素位置逐个相乘
@
为常见的矩阵运算
.dot()
与 @
运算结果一样
import numpy as np
a = np.arange(4).reshape(2, 2)
b = np.ones((2, 2))
print(a * b)
print(a @ b)
print(a.dot(b))
结果如下:
[[0. 1.]
[2. 3.]]
[[1. 1.]
[5. 5.]]
[[1. 1.]
[5. 5.]]
4.3 Universal functions
import numpy as np
a = np.arange(10).reshape(2, 5)
print(a)
print(a.max())
print(a.max(axis=0)) # [5 6 7 8 9]
print(a.max(axis=1)) # [4 9]
a.sort() # 排序
print(a)
通过指定 axis
的值可以在特定的维度上操作,axis=0
代表对最外层(第一层 [] 内的元素,其中每一个元素可能为一个矩阵)的元素操作,axis=1
代表对第二层元素操作,如:
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a)
print(a.sum(axis=0))
print(a.sum(axis=1))
print(a.sum(axis=2))
axis=0时,对两个大小均为 (2, 3) 的矩阵求和,得到大小为 (2, 3) 的矩阵;
axis=1时,对两个大小均为 (2, 3) 的矩阵中的所有行求和,得到大小为 (2, 4) 的矩阵;
axis=0时,对两个大小均为 (2, 3) 的矩阵中 3 个行矩阵的内部元素求和,得到大小为 (2, 3) 的矩阵;
结果如下:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
[[12 14 16 18]
[20 22 24 26]
[28 30 32 34]]
[[12 15 18 21]
[48 51 54 57]]
[[ 6 22 38]
[54 70 86]]
4.4 Index, slice, iterate
可以使用下表访问元素,可以截取片段,也可以按一定间隔选取元素:
import numpy as np
a = np.arange(0, 15)
print(a)
print(a[3:9]) # [3 4 5 6 7 8]
print(a[ : :3]) # [ 0 3 6 9 12]
print(a[ : : -1]) # reverse
for element in a:
print(element)
对于多维数组,支持同样的操作:
b = np.arange(25).reshape(5, 5)
print(b[2]) # row = 2
print(b[ :, : : -1]) # reverse each row
当数组有多维时,选取一部分可以使用 ...
替代多个 : : :
,如下面的语句等价:
a = np.ones((2, 3, 4))
print(a[1, ...])
print(a[1, :, :])
多维矩阵也支持遍历,遍历从外到内:
import numpy as np
a = np.ones((3, 5))
for row in a:
print(row)
结果如下:
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]
5. 拆分与合并
5.1 change shape
可以通过转置 T
或 reshape
改变矩阵的现状:
import numpy as np
a = np.ones((3, 5))
print(a.shape) # (3, 5)
print(a.T.shape) # (5, 3)
a = a.reshape(1, 15)
print(a.shape) # (1, 15)
5.2 数组合并
可以用 concatenate
合并数组,参数 axis
为 0 时按行合并,
import numpy as np
arr1 = np.array([[1,2,3], [4,5,6]])
arr2 = np.array([[7,8,9], [10,11,12]])
data = np.concatenate([arr1, arr2], axis=0)
print(data)
5.3 数组拆分
语法:split(ary, indices_or_sections, axis=0)
import numpy as np
a = np.arange(8).reshape(2, 4)
print(np.split(a, 2, 0)) # 按行分为 2 份
print(np.split(a, 4, 1)) # 按列分为 4 份
6. copy
复制 numpy 矩阵的方法有两类,浅拷贝与深拷贝
numpy 矩阵的变量名存储了矩阵内存地址的首地址,将矩阵变量名赋值给另一个变量后,实际上是一个矩阵的两个名字:
a = np.array([1, 2, 3, 4])
b = a
print(b is a) # equivalent
print(id(a), id(b))
但通过 array.copy()
可以深拷贝内存数据,得到一个新的矩阵:
c = np.array([1, 2, 3, 4])
d = c.copy()
print(c is d)
print(id(c), id(d))