Numpy入门(四)深入学习Numpy模块

时间:2024-03-27 09:24:07

1 linalg模块

import numpy as np
A = np.mat("0 1 2; 1 0 3; 4 -3 8")
A
matrix([[ 0,  1,  2],
        [ 1,  0,  3],
        [ 4, -3,  8]])
# 矩阵的逆
np.linalg.inv(A)
matrix([[-4.5,  7. , -1.5],
        [-2. ,  4. , -1. ],
        [ 1.5, -2. ,  0.5]])
A * np.linalg.inv(A)
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
A = np.mat("1 -2 1;0 2 -8;-4 5 9")
A
matrix([[ 1, -2,  1],
        [ 0,  2, -8],
        [-4,  5,  9]])
b = np.array([0,8,-9])
x = np.linalg.solve(A,b)
x
array([29., 16.,  3.])
np.dot(A,x)
matrix([[ 0.,  8., -9.]])
np.linalg.det(A)
1.9999999999999998

2 fft模块

from matplotlib.pyplot import *
x = np.linspace(0,2*np.pi,30)
wave = np.cos(x)
trans = np.fft.fft(wave)
plot(trans)
show()
D:\Anaconda3-5\lib\site-packages\numpy\core\numeric.py:492: ComplexWarning: Casting complex values to real discards the imaginary part
  return array(a, dtype, copy=False, order=order)

Numpy入门(四)深入学习Numpy模块

3 随机数模块

N = 10000
normal_values = np.random.normal(size = N)
plot(normal_values)
show()

Numpy入门(四)深入学习Numpy模块

4 排序

a = np.random.randint(0,100,size=10)
a
array([80,  5, 42,  5, 30, 34, 12, 37, 65,  2])
np.sort(a)
array([ 2,  5,  5, 12, 30, 34, 37, 42, 65, 80])
b = np.random.randn(10)
b
array([ 0.24423767, -0.17118507,  0.48413289, -0.10999024, -1.16224052,
       -0.59838132, -0.56166675,  0.51791264,  0.0882722 ,  0.01779734])
for each in zip(a ,b):
    print(each)
(80, 0.24423766862382038)
(5, -0.17118507409164932)
(42, 0.4841328947126019)
(5, -0.1099902424565808)
(30, -1.1622405164607184)
(34, -0.5983813182583405)
(12, -0.5616667452697109)
(37, 0.5179126359900825)
(65, 0.08827219948984628)
(2, 0.017797342769532515)
np.random.random(5)
array([0.57029857, 0.37006366, 0.82282303, 0.87245183, 0.68276258])

5 搜索

a = np.array([2,4,8])
np.argmax(a)
2
b = np.array([np.nan,2,4])
np.nanargmax(b)
2
np.argwhere(a<5)
array([[0],
       [1]], dtype=int64)
a=np.arange(7)
condition = (a%2) == 0
np.extract(condition,a)
array([0, 2, 4, 6])
np.nonzero(a)
(array([1, 2, 3, 4, 5, 6], dtype=int64),)