numpy: meshgrid方法

meshgrid方法用于对两个一维数组生成一个数值对(x, y)
例如,对于数组[1, 2]和[3, 4],可以生成4个数值对,分别为:
[1, 3], [2, 3], [1, 4], [2, 4]

meshgrid方法返回两个二维矩阵,分别存储所有键值对中的x值和y值

import numpy as np
a = [1, 2]
b = [3, 4]
c, d = np.meshgrid(a, b)
print(c)
# [[1 2]
#  [1 2]]
print(d)
# [[3 3]
#  [4 4]]

也就是说,meshgrid方法不直接返回数值对,而是分别返回数值对中x的集合和y的集合(这里的集合包含重复)

那meshgrid函数能用在哪里呢?

举个栗子,我们计算下列函数所有的取值,并对z进行可视化
在这里插入图片描述
利用meshgrid函数,我们可以这样做:

import numpy as np
import matplotlib.pyplot as plt
point = np.arange(-5, 5, 0.01)
xs, ys = np.meshgrid(point, point)
z = np.sqrt(xs ** 2 + ys ** 2)
print(z)
# [[7.07106781 7.06400028 7.05693985 ... 7.04988652 7.05693985 7.06400028]
#  [7.06400028 7.05692568 7.04985815 ... 7.04279774 7.04985815 7.05692568]
#  [7.05693985 7.04985815 7.04278354 ... 7.03571603 7.04278354 7.04985815]
#  ...
#  [7.04988652 7.04279774 7.03571603 ... 7.0286414  7.03571603 7.04279774]
#  [7.05693985 7.04985815 7.04278354 ... 7.03571603 7.04278354 7.04985815]
#  [7.06400028 7.05692568 7.04985815 ... 7.04279774 7.04985815 7.05692568]]
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
plt.show()

在这里插入图片描述

参考资料:

《利用python进行数据分析》

发布了19 篇原创文章 · 获赞 1 · 访问量 782

猜你喜欢

转载自blog.csdn.net/weixin_43901558/article/details/104767096
今日推荐