Numpy 中数组和矩阵的基本运算

来源:互联网 发布:淘宝店必须交保证金吗 编辑:程序博客网 时间:2024/05/21 19:46

1.建立矩阵

b = np.array([1, 2, 3])print b----------c = np.array([[1, 2, 3], [1, 2, 3]])#O:     [[1 2 3]         [1 2 3]]----------b = np.arange(12)print b#O:     [ 0  1  2  3  4  5  6  7  8  9 10 11]----------b = np.arange(12).reshape(3,4)print b#O:     [[ 0  1  2  3]         [ 4  5  6  7]         [ 8  9 10 11]]----------b = np.eye(3,3)print b#O:     [[ 1.  0.  0.]         [ 0.  1.  0.]         [ 0.  0.  1.]]----------c = np.eye(3,5)print c#O      [[ 1.  0.  0.  0.  0.]         [ 0.  1.  0.  0.  0.]         [ 0.  0.  1.  0.  0.]]

2.矩阵维度

import numpy as npb = np.arange(12).reshape(3, 4)print bprint b.shape#O      [[ 0  1  2  3]         [ 4  5  6  7]         [ 8  9 10 11]]        (3L, 4L)

3.求和,极值

b = np.arange(12).reshape(3, 4)print b.sum()#O      66print b.max()#O      11print b.min()#O  0print b.mean()#O      5.5test1 = np.array([[5, 10, 15],            [20, 25, 30],            [35, 40, 45]])#行求和test1.sum(axis=1)# 输出 array([30, 75, 120])#列求和test1.sum(axis=0)# 输出 array([60, 75, 90])

4.数组乘法

a = np.array([[1, 2],              [3, 4]])b = np.array([[5, 6],              [7, 8]])#按元素相乘 elementwiseprint a*b#输出     [[ 5 12]         [21 32]]#矩阵乘法print a.dot(b)#输出     [[19 22]         [43 50]]

5.元素运算

a = np.arange(4)print aprint a**2                  #squareprint np.exp(a)             #power of Eprint np.sqrt(a)            #rootprint np.floor(np.sqrt(a))  #round#OUT    [0 1 2 3]        [0 1 4 9]        [  1.           2.71828183   7.3890561   20.08553692]        [ 0.          1.          1.41421356  1.73205081]        [ 0.  1.  1.  1.]

6.转置

a = np.arange(12).reshape(3, 4)b = a.Tprint aprint b#OUT     [[ 0  1  2  3]         [ 4  5  6  7]         [ 8  9 10 11]]        [[ 0  4  8]         [ 1  5  9]         [ 2  6 10]         [ 3  7 11]]

7.数组删除指定,行列

z= np.arange(10).reshape(5, 2)print zz = np.delete(z, np.s_[1:3],axis = 0)print z#OUT    [[0 1]         [2 3]         [4 5]         [6 7]         [8 9]]        [[6 7]         [8 9]]z = np.delete(z, np.s_[0,2],axis = 0)print z#OUT    [[2 3]         [6 7]         [8 9]]z= np.arange(10).reshape(2, 5)print zz = np.delete(z, np.s_[0:2],axis = 1)print z#OUT    [[0 1 2 3 4]         [5 6 7 8 9]]        [[2 3 4]         [7 8 9]]

8.矩阵拼接

import numpy as npa = [[1, 2, 3],     [1, 2, 3]]b = [[4,4,4],    [4,4,4]]c = np.row_stack((a, b))print cc = np.column_stack((a, b))print c     #OUT    [[1 2 3]         [1 2 3]         [4 4 4]         [4 4 4]]        [[1 2 3 4 4 4]         [1 2 3 4 4 4]]
0 0
原创粉丝点击