Numpy入門(三)Numpy便捷函式
阿新 • • 發佈:2018-12-06
便捷函式
1 常用函式
import numpy as np
a = np.arange(-5,5)
signs = np.sign(a)
piecewises = np.piecewise(a,[a>0,a<0],[1,-1])
np.array_equal(signs,piecewises)
True
2 建立矩陣
A = np.mat('1 2 3; 4 5 6; 7 8 9')
A
matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
A.T
matrix([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
A = np.eye(2)
A
array([[1., 0.],
[0., 1.]])
B = 2*A
B
array([[2., 0.],
[0., 2.]])
np.bmat('A B;A B')
matrix([[1., 0., 2., 0.], [0., 1., 0., 2.], [1., 0., 2., 0.], [0., 1., 0., 2.]])
3 通用函式
通用函式的輸入是一組標量,輸出也是一組標量,他們通常可以對應於基本數學運算,如加減乘除
def ultimate_answer(a):
return np.zeros_like(a)
a = np.eye(3)
ultimate_answer(a)
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
a.flat
<numpy.flatiter at 0x2e247c0>
list(a.flat)
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]
a = np.arange(9)
np.add.reduce(a)
36
np.add.accumulate(a)
array([ 0, 1, 3, 6, 10, 15, 21, 28, 36])
4 算術運算
a = np.array([2,6,5])
b = np.array([1,2,3])
np.divide(a,b)
array([2, 3, 1])
np.divide(b,a)
array([0, 0, 0])
np.true_divide(a,b)
array([2. , 3. , 1.66666667])
np.true_divide(b,a)
array([0.5 , 0.33333333, 0.6 ])
from __future__ import division
a/b
array([2. , 3. , 1.66666667])
a//b
array([2, 3, 1])
a = np.arange(-4,4)
a
array([-4, -3, -2, -1, 0, 1, 2, 3])
np.remainder(a,2)
array([0, 1, 0, 1, 0, 1, 0, 1])
np.mod(a,2)
array([0, 1, 0, 1, 0, 1, 0, 1])
a%2
array([0, 1, 0, 1, 0, 1, 0, 1])
np.fmod(a,2)
array([ 0, -1, 0, -1, 0, 1, 0, 1])
from matplotlib.pyplot import plot
from matplotlib.pyplot import show
a = 1
b =2
t = np.linspace(-np.pi,np.pi,201)
x = np.sin(a*t +np.pi/2)
y = np.sin(b*t)
plot(x)
[<matplotlib.lines.Line2D at 0x7f6c02908f50>]
show()