python - 如何将数据从 meshgrid 格式转换为数组,反之亦然 : Python

标签 python arrays numpy

我有一个数据集 data = f(x,y)。数据以网格格式提供。我想将它转换成一个数组,这样每一行都将以 [x,y,data] 格式排序。另外,反过来怎么办?

import numpy as np

x = np.arange(-5, 5, 0.1)
y = np.arange(-4, 4, 0.1)
xx, yy = np.meshgrid(x, y)
data = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)

print(data)  #Now it is in meshgrid format

最佳答案

您可以使用以下方法 reshape 数据:

<强>1。网格格式

import numpy as np

x = np.arange(-5, 5, 2)
y = np.arange(-4, 4, 2)
xx, yy = np.meshgrid(x, y)
data = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)

print(data)  # In meshgrid format

输出:

[[-0.00386885 -0.00529407 -0.05655279 -0.05655279 -0.00529407]
 [-0.02288393  0.03232054 -0.19178485 -0.19178485  0.03232054]
 [-0.00529407  0.04579094  0.84147098  0.84147098  0.04579094]
 [-0.02288393  0.03232054 -0.19178485 -0.19178485  0.03232054]]

<强>2。列格式:

z = len(x)*len(y)
a = np.reshape(xx, z)
b = np.reshape(yy, z)
c = np.reshape(data, z)

new = np.c_[a, b, c]

print(new) # In an array ordered like [x, y, data]

输出:

[[-5.00000000e+00 -4.00000000e+00 -3.86884558e-03]
 [-3.00000000e+00 -4.00000000e+00 -5.29407000e-03]
 [-1.00000000e+00 -4.00000000e+00 -5.65527936e-02]
 [ 1.00000000e+00 -4.00000000e+00 -5.65527936e-02]
 [ 3.00000000e+00 -4.00000000e+00 -5.29407000e-03]
 [-5.00000000e+00 -2.00000000e+00 -2.28839270e-02]
 [-3.00000000e+00 -2.00000000e+00  3.23205413e-02]
 [-1.00000000e+00 -2.00000000e+00 -1.91784855e-01]
 [ 1.00000000e+00 -2.00000000e+00 -1.91784855e-01]
 [ 3.00000000e+00 -2.00000000e+00  3.23205413e-02]
 [-5.00000000e+00  0.00000000e+00 -5.29407000e-03]
 [-3.00000000e+00  0.00000000e+00  4.57909428e-02]
 [-1.00000000e+00  0.00000000e+00  8.41470985e-01]
 [ 1.00000000e+00  0.00000000e+00  8.41470985e-01]
 [ 3.00000000e+00  0.00000000e+00  4.57909428e-02]
 [-5.00000000e+00  2.00000000e+00 -2.28839270e-02]
 [-3.00000000e+00  2.00000000e+00  3.23205413e-02]
 [-1.00000000e+00  2.00000000e+00 -1.91784855e-01]
 [ 1.00000000e+00  2.00000000e+00 -1.91784855e-01]
 [ 3.00000000e+00  2.00000000e+00  3.23205413e-02]]

关于python - 如何将数据从 meshgrid 格式转换为数组,反之亦然 : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55660090/

相关文章:

python - 通过套接字发送和接收字节,具体取决于您的互联网速度

java - ArrayIndexOutOfBoundsException 计算平均值

javascript - Javascript 数组中的动态串联

python - 在内置函数或模块函数中可以创建点源 nxn 数组吗?

python - 如何从python中的整个3D数组中提取上限值

python - 如何使用 SQLalchemy 获取列表中提供的键的所有行?

python - Python 3 时来自 BeautifulSoup 的 "illegal multibyte sequence"错误

python - CPython中函数对象和代码对象的关系

c++ - 如何创建模板化对象的数组/vector

python - 为什么 numpy.power 比 in-lining 慢 60 倍?