完全版numpy教程 (opens new window)

# NumPy使用简洁版 - 开始

import numpy as np
1
# 创建零元素
x = np.zeros((3, 2))
print(x)
print(x.shape)
# res:
# [[0. 0.]
# [0. 0.]
# [0. 0.]]
1
2
3
4
5
6
7
8
# 创建1元素
x = np.ones((1, 2, 3))
print(x)
print(x.shape)
## res:
# [[[1. 1. 1.]
# [1. 1. 1.]]]
1
2
3
4
5
6
7
# 创建递增递减的数组
x = np.arange(3, 7, 1)
print(x)
print(x.shape)
## res:[3 4 5 6]
x = np.arange(7, 3, -1)
print(x)
print(x.shape)
## res:[7 6 5 4]
1
2
3
4
5
6
7
8
9
# 返回介于某个区间,等间距分布的数
x = np.linspace(0, 1, 5, dtype=float)
print(x)
print(x.shape)
# res:[0.   0.25 0.5  0.75 1.  ]
1
2
3
4
5
# 随机数字
x = np.random.rand(2, 4)
print(x)
print(x.dtype)
# res:
# [[0.27368366 0.4409401  0.75639646 0.68940181]
# [0.99276879 0.10924652 0.8508327  0.02693879]]
1
2
3
4
5
6
7
# 改变数据类型
x = x.astype(int)
print(x)
# res:
# [[0 0 0 0]
# [0 0 0 0]]
1
2
3
4
5
6
# 加减乘除运算
a = np.array([1, 2, 3], dtype=float)
b = np.array([4, 5, 6], dtype=float)
print(a + b)
print(a - b)
print(a * b)
print(a / b)
## res:
## [5. 7. 9.]
## [-3. -3. -3.]
## [ 4. 10. 18.]
## [0.25 0.4  0.5 ]
1
2
3
4
5
6
7
8
9
10
11
12
# 向量的点乘运算
a = np.array([1, 2, 3], dtype=int)
b = np.array([4, 5, 6], dtype=int)
print(np.dot(a, b))
## res:32
1
2
3
4
5
# 矩阵的乘法运算
a = np.array([[1, 2], [3, 4]], dtype=int)
b = np.array([[2, 0], [0, 2]], dtype=int)
print(a @ b)
## res:32
1
2
3
4
5
# 求根
a = np.array([1, 2, 3], dtype=int)
x = np.sqrt(a)
x = x.astype(float)
print(x)
1
2
3
4
5
# sin、cos、tan
x = np.sin(a)
print(x)
x = np.cos(a)
print(x)
x = np.tan(a)
print(x)
# res:
# [0.84147098 0.90929743 0.14112001]
# [ 0.54030231 -0.41614684 -0.9899925 ]
# [ 1.55740772 -2.18503986 -0.14254654]
1
2
3
4
5
6
7
8
9
10
11
# 次方运算、对数运算
a = np.array([1, 2, 3], dtype=int)
a = np.power(a, 2)
print(a)
a = np.log(a)
print(a)
## [1 4 9]
1
2
3
4
5
6
7
# 直接数乘矩阵
a = np.array([1, 2, 3], dtype=int)
print(a * 3)
## res:[3 6 9]
1
2
3
4
# 不同尺寸的数组也可以运算、自动补全维数
# [1  1  1 ]    [0 1 2]
# [10 10 10] 和 [0 1 2]
# [20 20 20]    [0 1 2]
a = np.array([[1], [10], [20]])
b = np.array([0, 1, 2])
print(a + b)
# res:
# [[ 1  2  3]
# [10 11 12]
# [20 21 22]]
1
2
3
4
5
6
7
8
9
10
11
# 数组最值,argmax/min是最值的位置
x = np.array([1, 2, 3, 4, 5])
print('最小:', x.min(), '最小位置:', x.argmin())
print('最大:', x.max(), '最大位置:', x.argmax())
print('总和:', x.sum())
print('平均值:', x.mean())
print('中位数:', np.median(x))
print('方差:', np.var(x))
print('标准差:', np.std(x))

# res:
# 最小: 1 最小位置: 0
# 最大: 5 最大位置: 4
# 总和: 15
# 平均值: 3.0
# 中位数: 3.0
# 方差: 2.0
# 标准差: 1.4142135623730951
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 多维数组相加,axis=0按行相加,axis=1按列相加
a=np.array([[1,2,3,4,5],
            [6,7,8,9,10]])
print(a.sum(axis=0))
## res:[ 7  9 11 13 15]
print(a.sum(axis=1))
## res:[15 40]
1
2
3
4
5
6
7
# 获取与筛选元素
a=np.array([[1,2,3,4,5],
            [6,7,8,9,10]])
print(a[0,1])
print(a[a<4])
## 获取第0行,0-1列的数据
print(a[0,0:2])
## 获取第0行,所有列的元素
print(a[0,:])
print(a[(a>3)&(a%2==0)])

# res:
# 2
# [1 2 3]
# [1 2]
# [1 2 3 4 5]
# [ 4  6  8 10]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 跨度取数
a=np.array([1,2,3,4,5,6,7,8,9])
print(a[0:9:2])
print(a[0:9:3])
print(a[9:3:-2])
## 倒序数组的常用写法
print(a[::-1])

# res:
# [1 3 5 7 9]
# [1 4 7]
# [9 7 5]
# [9 8 7 6 5 4 3 2 1]
1
2
3
4
5
6
7
8
9
10
11
12
13
print('==================================分割线')
1
# numpy操作图片的例子
from PIL import Image
im=Image.open('dog.png')
# im.show()
im=np.array(im)
print('行数、列数、通道数(颜色分量)',im.shape)
print('某个像素点的RGB颜色',im[100,100])
im_r=im[:,:,0]# 获取第0层通道的所有,即红色
# Image.fromarray(im_r).show()

dog=np.array(Image.open('dog.png'))
img=np.array(Image.open('dog.png'))
im_blend=dog*0.5+img*0.5 # 合成两张图片,大小要一样
im_blend=im_blend.astype(np.uint8)
# Image.fromarray(im_blend).show()


# 降采样,隔2取一次
img_down=im_blend[::2,::2,:]
# Image.fromarray(img_down).show()

# 翻转图片,第1维是按行翻转
img_down=im_blend[::-1,:,:]
# Image.fromarray(img_down).show()

# 裁剪图片
img_down=im_blend[1:400,200:600,:]
# Image.fromarray(img_down).show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# matplotlib的使用
from matplotlib import pyplot as plt
## 创建递增的数组x,表示区间
# x = np.arange(1, 10,1)
## 1生成的不够平滑,太直线了
x = np.arange(1, 10,0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
# subplot(m,n,p)或者subplot(m n p)。
#
# subplot是将多个图画到一个平面上的工具
# 其中,m表示是图排成m行,n表示图排成n列
# p表示图所在的位置,p=1表示从左到右从上到下的第一个位置
# 两行一列
# 激活第一个 subplot
plt.subplot(2,  1,  1)
# 绘制第一个图像
plt.plot(x, y_sin)
plt.title('Sine')

# 将第二个 subplot 激活,并绘制第二个图像
plt.subplot(2,  1,  2)
plt.plot(x, y_cos)
plt.title('Cosine')
# 展示图像
plt.show()

# 柱状图
x =  [5,8,10]
y =  [12,16,6]
x2 =  [6,9,11]
y2 =  [6,15,7]
plt.bar(x, y, align =  'center')
plt.bar(x2, y2, color =  'g', align =  'center')
plt.title('Bar graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

# histogram() 函数是数据的频率分布的图形表示
# 水平尺寸相等的矩形对应于类间隔,称为 bin,变量 height 对应于频率
a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
np.histogram(a,bins =  [0,20,40,60,80,100])
hist,bins = np.histogram(a,bins =  [0,20,40,60,80,100])
print (hist)
print (bins)

plt.hist(a,bins =  [0,20,40,60,80,100])
plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

# NumPy使用简洁版 - 结束