Numpy入门(三)Numpy便捷函数

便捷函数

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()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42363997/article/details/83827528
今日推荐