NumPy
import numpy as np
矩阵的拼接和拆分
首先,我们来看如何拼接矩阵。使用numpy库中的numpy.concatenate
函数可以实现矩阵的拼接。该函数可以指定拼接的方向(横向或纵向)。以下示例演示了如何拼接两个矩阵:
import numpy as np
# 创建两个矩阵
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# 横向拼接
concatenated_matrix = np.concatenate((matrix1, matrix2), axis=1)
print(concatenated_matrix)
# 纵向拼接
concatenated_matrix = np.concatenate((matrix1, matrix2), axis=0)
print(concatenated_matrix)
输出结果:
[[1 2 5 6]
[3 4 7 8]]
[[1 2]
[3 4]
[5 6]
[7 8]]
接下来,我们来看如何拆分矩阵。使用numpy库中的numpy.split
函数可以实现矩阵的拆分。该函数可以指定拆分的方向(横向或纵向)和拆分的位置。以下示例演示了如何拆分矩阵:
import numpy as np
# 创建一个矩阵
matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# 按列拆分
split_matrices = np.split(matrix, 4, axis=1)
for split_matrix in split_matrices:
print(split_matrix)
# 按行拆分
split_matrices = np.split(matrix, 3, axis=0)
for split_matrix in split_matrices:
print(split_matrix)
输出结果:
[[1]
[5]
[9]]
[[2]
[6]
[10]]
[[3]
[7]
[11]]
[[4]
[8]
[12]]
[[1 2 3 4]]
[[5 6 7 8]]
矩阵元素搜索、排序操作
在numpy
库中,可以使用以下函数进行矩阵元素的搜索和排序操作:
numpy.argmax()
: 返回数组中最大元素的索引。numpy.argmin()
: 返回数组中最小元素的索引。numpy.where()
: 返回满足条件的元素的索引。numpy.sort()
: 对数组进行排序。numpy.argsort()
: 返回数组排序后的索引。numpy.sort(axis=0)
: 对数组沿指定轴进行排序。numpy.searchsorted()
: 返回将元素插入到数组中时的索引,以保持数组的排序。
下面是这些函数的详细说明和示例:
import numpy as np
# 创建一个矩阵
matrix = np.array([[3, 2, 1], [6, 4, 5], [9, 8, 7]])
# 搜索操作
max_index = np.argmax(matrix) # 返回最大元素的索引
min_index = np.argmin(matrix) # 返回最小元素的索引
indices = np.where(matrix > 5) # 返回满足条件的元素的索引
print("最大元素的索引:", max_index)
print("最小元素的索引:", min_index)
print("满足条件的元素的索引:", indices)
# 排序操作
sorted_matrix = np.sort(matrix) # 对数组进行排序
sorted_indices = np.argsort(matrix) # 返回排序后的索引
sorted_matrix_axis0 = np.sort(matrix, axis=0) # 对数组沿第0轴进行排序
search_index = np.searchsorted(sorted_matrix, 5) # 返回5在排序后数组中的索引
print("排序后的矩阵:", sorted_matrix)
print("排序后的索引:", sorted_indices)
print("沿第0轴排序后的矩阵:", sorted_matrix_axis0)
print("数字5插入的索引:", search_index)
输出结果:
最大元素的索引: 6
最小元素的索引: 2
满足条件的元素的索引: (array([1, 2, 2]), array([0, 0, 1]))
排序后的矩阵: [[1 2 3]
[4 5 6]
[7 8 9]]
排序后的索引: [[2 1 0]
[1 2 0]
[2 1 0]]
沿第0轴排序后的矩阵: [[3 2 1]
[6 4 5]
[9 8 7]]
数字5插入的索引: 5
numpy库实现图像翻转
以下是一个简单的示例代码,展示了如何使用NumPy库将图像水平翻转:
import numpy as np
import matplotlib.pyplot as plt
# 读取图像
image = plt.imread(r"D:\绘画\画集\芙莉莲.png")
# 将图像水平翻转
flipped_image = np.fliplr(image)
# 显示原始图像和翻转后的图像
fig, axes = plt.subplots(1, 2)
axes[0].imshow(image)
axes[0].set_title('Original Image')
axes[1].imshow(flipped_image)
axes[1].set_title('Flipped Image')
# 隐藏坐标轴
for ax in axes:
ax.axis('off')
# 显示图像
plt.show()
运行结果:
要进行垂直翻转,可以使用np.flipud()
函数,代码如下:
import numpy as np
import matplotlib.pyplot as plt
# 读取图像
image = plt.imread('image.jpg')
# 将图像垂直翻转
flipped_image = np.flipud(image)
# 显示原始图像和翻转后的图像
fig, axes = plt.subplots(1, 2)
axes[0].imshow(image)
axes[0].set_title('Original Image')
axes[1].imshow(flipped_image)
axes[1].set_title('Flipped Image')
# 隐藏坐标轴
for ax in axes:
ax.axis('off')
# 显示图像
plt.show()
实验思考题
1、创建一个长度为20的一位ndarray对象,要求前5个数据为0,中间10个为1,最后5个为10
import numpy as np
arr1 = np.zeros(5)
arr2 = np.ones(10)
arr3 = np.full(5, 10)
#合并
result = np.concatenate((arr1, arr2, arr3))
print(result)
2、利用optimize()求函数最小值
import numpy as np
from pylab import *
from scipy import optimize
def f(x):
return x**2+np.cos(x)
x = np.arange(-2, 2, 0.1)
plt.plot(x, f(x))
plt.show()#作图可看出求值范围
res = optimize.fmin_bfgs(f, 0)
#0表示初始化的参数
print(res[0])
运行结果:
Optimization terminated successfully.
Current function value: 1.000000
Iterations: 0
Function evaluations: 2
Gradient evaluations: 1
0
3、利用Matplotlib包作图,绘制tan(x)图像
import numpy as np
import matplotlib.pyplot as plt
import math
x=np.arange(-math.pi,math.pi,0.01)
y=np.tan(x)
plt.plot(x,y,color='blue',linestyle='dotted')
plt.title("tan(x)")
plt.xlabel("x")
plt.ylabel("y")
plt.show()