1、numpy基础

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import numpy as np

array = np.array([[1, 2, 3], [4, 5, 6]]) # 把列表转成矩阵
print(array)
print('number of dim:', array.ndim) # 维度
print('shape:', array.shape)
print('size:', array.size)

a = np.array([2, 23, 4], dtype=np.float32) # 指定格式
print(a.dtype)

a = np.arange(10, 20, 2)
print(a)

a = np.arange(12).reshape((3, 4))
print(a)

a = np.linspace(1, 10, 5) # 1到10分成5分
print(a)

2、numpy数组运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import numpy as np

a = np.array([10,20,30,40])
b = np.array(4)
print(a,b)
c = a +b
print(c)
c = b ** 2
print(c)
c = 10*np.sin(a)
print(c)

print(b)
print(b<3)


# 矩阵相乘
a = [[1,2],[3,4]]
b = [[2,3],[4,5]]
c = np.multiply(a,b) # 对应元素相乘
c_dot = np.dot(a,b) # 矩阵相乘
print(c)
print(c_dot)

a= np.random.random((2,4))
print(a.max())
print(a.sum())
a = [[1,2],[3,4]]
print(np.argmax(a)) # 找到最大的位置
print(np.mean(a)) # 平均值
print(np.median(a)) # 中位数
print(np.cumsum(a)) # 累加求和
print(np.diff(a)) # 累差
print(np.nonzero(a)) # 返回出非0元素的行列

a = np.arange(14,2,-1)
print(a.T) # 矩阵转置
print(np.transpose(a))

print(np.clip(a,5,9)) # 小于5的变成5,大于9的变成9

a= np.arange(3,15).reshape((3,4))
print(a)
print(a.flatten()) # flatten返回的是个数组
for item in a.flat: # flat返回的是个对象
print(item)

A= np.array([1,1,1])
B = np.array([2,2,2])
C = np.vstack((A,B)) # 上下合并
D= np.hstack((A,B)) # 左右合并
print(C)
print(D)

print(A[np.newaxis,:]) # 将一行序列变成一列的序列


# 数组分割
A = np.arange(12).reshape((3,4))
print(np.split(A,3))
print(np.vsplit(A,3))
print(np.hsplit(A,2))