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

xiaoxiao2021-02-27  210

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 np b = np.arange(12).reshape(3, 4) print b print 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 66 print b.max() #O 11 print b.min() #O 0 print b.mean() #O 5.5 test1 = 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]]) #按元素相乘 elementwise print a*b #输出 [[ 5 12] [21 32]] #矩阵乘法 print a.dot(b) #输出 [[19 22] [43 50]]

5.元素运算

a = np.arange(4) print a print a**2 #square print np.exp(a) #power of E print np.sqrt(a) #root print 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.T print a print 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 z z = 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 z z = 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 np a = [[1, 2, 3], [1, 2, 3]] b = [[4,4,4], [4,4,4]] c = np.row_stack((a, b)) print c c = 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]]
转载请注明原文地址: https://www.6miu.com/read-11169.html

最新回复(0)