1.Numpy简介
numpy是python中用于科学计算的核心库。它提供了高性能的多维数组的对象,以及相关工具。
2.创建数组
一维数组:
import numpy as np
>>> a = np.array([1, 2, 3])
>>> print(type(a))
<class 'numpy.ndarray'>
>>> print(a.shape)
(3,)#元素个数
>>> print(a[0])
1
>>> a[0]=8
>>> print(a)
[8 2 3]
二维数组:
b = np.array([[1,2,3],[4,5,6]])
>>> print(b.shape)
(2, 3)#2行3列
>>> b = np.array([[1,2,3],[4,5,6]])
>>>print(b[0,0])
1
>>> print(b[0,1])
2
>>>print(b[1,0])
4
3.数组访问
1.切片访问:
import numpy as np
>>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> b = a[:2, 1:3]
>>> print(b)
[[2 3]
[6 7]]
>>> print(a[0, 1])
2
>>> print(b[0, 0])
2
>>> row_r1 = a[1, :]
>>> row_r2 = a[1:2, :]
>>> print(row_r1, row_r1.shape)
[5 6 7 8] (4,)
>>> print(row_r2, row_r2.shape)
[[5 6 7 8]] (1, 4)
>>> col_r1 = a[:, 1]
>>> col_r2 = a[:, 1:2]
>>> print(col_r1, col_r1.shape)
[ 2 6 10] (3,)
>>> print(col_r2, col_r2.shape)
[[ 2]
[ 6]
[10]] (3, 1)
2.整型数组访问
构建成一个新数组:
>>> a = np.array([[1,2],[3,4],[4,5]])
>>> print(a[[0,1,2],[0,1,0]])
[1 4 4]
>>> print(np.array([a[0, 0], a[1, 1], a[2, 0]]))
[1 4 4]
>>> print(a[[0, 0], [1, 1]])
[2 2]
>>> print(np.array([a[0, 1], a[0, 1]]))
[2 2]
4.数据类型
>>> import numpy as np
>>> x = np.array([1, 2])
>>> print(x.dtype)
int32#和电脑位数没有关系
>>> x = np.array([1.0, 2.0])
>>> print(x.dtype)
float64
>>> x = np.array([1 ,2], dtype=np.int64)
>>> print(x.dtype)
int64
5.数组计算
1.基本运算
>>> import numpy as np
>>> a = np.arange(24)
>>> a = a.reshape(4,6)
>>> 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]]
>>> b = a-2
>>> print(b)
[[-2 -1 0 1 2 3]
[ 4 5 6 7 8 9]
[10 11 12 13 14 15]
[16 17 18 19 20 21]]
>>> print(a*b)#矩阵卷积运算
[[ 0 -1 0 3 8 15]
[ 24 35 48 63 80 99]
[120 143 168 195 224 255]
[288 323 360 399 440 483]]
#矩阵相乘
>>> import numpy as np
>>> a = np.arange(24)
>>> a = a.reshape(4,6)
>>> 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]]
>>> b = a-2
>>> print(b)
>>> c = b.T
[[ 25 115 205 295]
[ 43 349 655 961]
[ 61 583 1105 1627]
[ 79 817 1555 2293]]
>>> print(np.dot(a,c))
[[-2 -1 0 1 2 3]
[ 4 5 6 7 8 9]
[10 11 12 13 14 15]
[16 17 18 19 20 21]]
2.矩阵转置
>>> import numpy as np
>>> a = np.array([[0, 1],[2, 3]])
>>> print(a)
[[0 1]
[2 3]]
>>> print(a.T)
[[0 2]
[1 3]]