首页 > 解决方案 > 如何将一组数据转换为矩阵和向量

问题描述

假设我在一个 .txt 文件中有这么庞大的数据集,该文件具有以下结构:第一列和第二列表示离散的二维域,第三列表示在离散 X 和 Y 轴的每个点上计算的值。下面给出的示例

x  y  z
-1 -1 100
-1 0 50
-1 1 100
0 -1 50
0 0 0
0 1 50
1 -1 100
0 -1 50
1 1 100

看起来很愚蠢,但我一直在努力将这些数据转换为向量和矩阵,例如 X = [-1, 0, 1], Y = [-1, 0, 1] 和 Z = [[100, 50, 100 ]、[50、0、50]、[100、50、100]]。我使用 numpy 经历了许多技术和方法,但无法成功!

作为奖励:将这些数据转换为向量和矩阵,就像我描述的那样,是使用 matplotlib 以 3dscatter 或 3dcountour 类型绘制它的好方法吗?

标签: arraysnumpymatplotlibmatrixscientific-computing

解决方案


要绘制散点图,您无需对数据执行任何操作。只需按原样绘制那里的列。

要获得您想要的值,您可以获取 x 和 y 列的唯一元素,并根据这些维度重塑 z 列。

u="""x  y  z
-1 -1 100
-1 0 50
-1 1 100
0 -1 50
0 0 0
0 1 50
1 -1 100
1 0 50
1 1 100"""

import io
import numpy as np

data = np.loadtxt(io.StringIO(u), skiprows=1)

x = np.unique(data[:,0])
y = np.unique(data[:,1])
Z = data[:,2].reshape(len(x), len(y))

print(Z)

印刷

[[100.  50. 100.]
 [ 50.   0.  50.]
 [100.  50. 100.]]

不同的 y 坐标现在沿着数组的第二个轴,这对于使用 matplotlib 绘图是相当不寻常的。

因此,要使用等高线绘制网格值,您需要对所有三列进行相同的整形并转置(.T)它们。

import matplotlib.pyplot as plt

X = data[:,0].reshape(len(x), len(y)).T
Y = data[:,1].reshape(len(x), len(y)).T
Z = data[:,2].reshape(len(x), len(y)).T

plt.contour(X,Y,Z)
plt.show()

在此处输入图像描述


推荐阅读