VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • 数据分析和科学计算可视化(5)

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
63
64
65
66
67
68
69
70
71
72
分段函数
 
>>> x = np.random.randint(0, 10, size=(1,10))
>>> x
array([[0, 4, 3, 3, 8, 4, 7, 3, 1, 7]])
>>> np.where(x<5, 0, 1)            # 小于5的元素值对应0,其他对应1
array([[0, 0, 0, 0, 1, 0, 1, 0, 0, 1]])
>>> np.piecewise(x, [x<4, x>7], [lambda x:x*2, lambda x:x*3])
                                   # 小于4的元素乘以2
                                   # 大于7的元素乘以3
                                   # 其他元素变为0
array([[ 0,  0,  6,  6, 24,  0,  0,  6,  2,  0]])
 
 
计算唯一值以及出现次数
 
>>> x = np.random.randint(0, 10, 7)
>>> x
array([8, 7, 7, 5, 3, 8, 0])
>>> np.bincount(x)   # 元素出现次数,0出现1次,
                     # 1、2没出现,3出现1次,以此类推
array([1, 0, 0, 1, 0, 1, 0, 2, 2], dtype=int64)
>>> np.sum(_)        # 所有元素出现次数之和等于数组长度
7
>>> np.unique(x)     # 返回唯一元素值
array([0, 3, 5, 7, 8])
 
 
矩阵运算
 
>>> a_list = [3, 5, 7]
>>> a_mat = np.matrix(a_list)            # 创建矩阵
>>> a_mat
matrix([[3, 5, 7]])
>>> a_mat.T                              # 矩阵转置
matrix([[3],
        [5],
        [7]])
>>> a_mat.shape                          # 矩阵形状
(1, 3)
>>> a_mat.size                           # 元素个数
3
>>> a_mat.mean()                         # 元素平均值
5.0
>>> a_mat.sum()                          # 所有元素之和
15
>>> a_mat.max()                          # 最大值
7
 
>>> a_mat.max(axis=1)                    # 横向最大值
matrix([[7]])
>>> a_mat.max(axis=0)                    # 纵向最大值
matrix([[3, 5, 7]])
>>> b_mat = np.matrix((1, 2, 3))         # 创建矩阵
>>> b_mat
matrix([[1, 2, 3]])
>>> a_mat * b_mat.T                      # 矩阵相乘
matrix([[34]])
 
>>> c_mat = np.matrix([[1, 5, 3], [2, 9, 6]]) # 创建二维矩阵
>>> c_mat
matrix([[1, 5, 3],
        [2, 9, 6]])
>>> c_mat.argsort(axis=0)                     # 纵向排序后的元素序号
matrix([[0, 0, 0],
        [1, 1, 1]], dtype=int64)
>>> c_mat.argsort(axis=1)                     # 横向排序后的元素序号
matrix([[0, 2, 1],
        [0, 2, 1]], dtype=int64)
>>> d_mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> d_mat.diagonal()                          # 矩阵对角线元素
matrix([[1, 5, 9]])

相关教程