numpy使用

���Ľ�������л�����Ķ�

使用array创建矩阵

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import numpy as np
#创建向量/矩阵
a=np.array([5,10,15,20])
b=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
#输出行列数
a.shape
b.shape
b.shape[0]
#修改行列数
b.shape=4,3
c=b.reshape((2,-1)) #此处b和c共享内存
#转置
b.T
#指定数据类型
d=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],dtype=np.float)
#转换数据类型
f=d.astype(np.int) #np.bool/np.complex

使用函数创建矩阵**

1
2
3
4
5
6
7
8
9
#等差(指定公差)
a=np.arange(1,5,0.5)

#等差(指定个数)
b=np.linspace(1,10,10)
b=np.linspace(1,10,10, endpoint=False) #endpoint指定是否包括终值

#等比
c=np.logspace(1,4,4,endpoint=True,base=2)

存取、切片**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#选取指定行/列
a=np.arange(1,10)
print('a=',a)
#获取某个元素
print('a[3]=',a[3])
#获取第3-6个元素,左必右开
print('a[3:6]=',a[3:6])
#省略开始下标,表示从0开始
print('a[:]=',a[:5])
#步长为2
print('a[1:9:2]=',a[1:9:2])
#步长为-1,即翻转
print('a[::-1]=',a[::-1])
#切片数据是原数组的一个视图,与原数组共享内容空间
b = a[2:5]
b[0] = 200
print(a)

随机生成**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#均匀分布的随机数
a=np.random.rand(10)
#指定shape
b = np.random.rand(3,2)
print('a= ',a)
print('b= \n',b)
#正态分布的随机数, eg.N(3, 6.25)
c = 2.5 * np.random.randn(2, 4) + 3
print('c= ',c)
#0-4整数
d = np.random.randint(5, size=(2, 4))
print('d= \n',d)
#洗牌
e= np.arange(10)
print('e= ',e)
np.random.shuffle(e)
print('e= ',e)

使用bool数组存取**

1
2
3
4
5
6
7
8
9
10
11
12
13
#大于0.5的元素索引
print (a > 0.5)

#大于0.5的元素
b = a[a > 0.5]
print('b= ',b)

#将数组b中大于0.5的元素截取成0.5
b[b > 0.5] = 0.5
print('b= ',b)

#a不受影响,此处a和b不共享内存
print('a= ',a)

计算(点乘、求和…)**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#创建矩阵A和B
A=np.array([[1,1],[0,1]])
B=np.array([[2,0],[3,4]])

#元素相乘element-wiseproduct
A*B

#点乘
A.dot(B)
np.dot(A,B)

#求和
B.sum(axis=1)
B.sum(axis=1,keepdims=True)
#max,min,sqrt,exp...

meshgrid**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

#meshgrid用于从数组a和b产生网格
u = np.linspace(-3, 3, 101)
x, y = np.meshgrid(u, u)

z = x*y*np.exp(-(x**2 + y**2)/2) / math.sqrt(2*math.pi)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, cmap=cm.coolwarm, linewidth=0.1)

#eg
np.arange(0,60,10).reshape((-1,1))+np.arange(6)
array([[ 0, 1, 2, 3, 4, 5],
[10, 11, 12, 13, 14, 15],
[20, 21, 22, 23, 24, 25],
[30, 31, 32, 33, 34, 35],
[40, 41, 42, 43, 44, 45],
[50, 51, 52, 53, 54, 55]])
0%