import numpy as np
a = np.array([0, 2, 4])
a * 2 # array([0, 4, 8])
a = [0, 2, 4]
a * 2 # [0, 2, 4, 0, 2, 4]
import array
array.array('i', [0, 2, 4]) * 2 # array('i', [0, 2, 4, 0, 2, 4])
[i*2 for i in a] # [0, 4, 8]
res = []
for i in a:
res.append(i * 2)
res # [0, 4, 8]
data = range(10**6)
%%time
res = []
for i in data:
res.append(i * 2)
res # Wall time: 171 ms
%time res = [i*2 for i in data] # Wall time: 110 ms
arr = np.array(data)
%time res = arr * 2 # Wall time: 19.1 ms
a = np.array([0, 2, 4])
a + 2 # array([2, 4, 6])
a - 2 # array([-2, 0, 2])
a * 2 # array([0, 4, 8])
a / 2 # array([0., 1., 2.])
X = np.arange(1, 16).reshape((3, 5))
X.shape
X // 2 # 整除
X ** 2 # 幂运算
X % 2 # 模运算
1 / X # 求倒数
np.abs(X - 2) # 求绝对值
np.sin(X) # 求正弦
np.cos(X) # 求余弦
np.tan(X) # 求正切
np.exp(X) # X的每个函数的e次方
from math import e
e ** 3 # 20.085536923187664即(2.00855369e+01)
np.p(3, X) # 3为底的X次方
3 ** X
np.log(X) # 以自然对数e为底
np.log2(X) # 以2为底
2 ** 1.5849625 # 2.999999998500398
np.log10(X) # 以10为底
10 ** 0.30103 # 2.0000000199681045
A = np.arange(4).reshape((2, -1))
B = np.full((2, 2), 10)
A + B # numpy中对应元素做运算
A - B
A * B
A / B
A = np.arange(4).reshape((2, -1))
B = np.array([10, 20, 30, 40]).reshape(2, -1)
A.dot(B) # 标准矩阵乘法运算:用A矩阵中的每一行和B矩阵中的每一列对应位置做相乘,然后相加
invA = np.linalg.inv(A) # 矩阵的逆
A.dot(invA)
invA.dot(A)
A = np.arange(6).reshape((2, -1))
invA = np.linalg.inv(A)
invA # LinAlgError: Last 2 dimensions of the array must be square,不是方阵,不能求得逆矩阵,只能求伪逆矩阵
pinvA = np.linalg.pinv(A) # 伪逆矩阵
pinvA
A.dot(pinvA)
A.T # 矩阵的转置,行变列,列变行
注:代码来自《Python全栈工程师特训班》课程