Python丨科学计算和可视化

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库中,可以使用以下函数进行矩阵元素的搜索和排序操作:

  1. numpy.argmax(): 返回数组中最大元素的索引。
  2. numpy.argmin(): 返回数组中最小元素的索引。
  3. numpy.where(): 返回满足条件的元素的索引。
  4. numpy.sort(): 对数组进行排序。
  5. numpy.argsort(): 返回数组排序后的索引。
  6. numpy.sort(axis=0): 对数组沿指定轴进行排序。
  7. 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()
  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值