如何将一组数据转换为矩阵和向量

问题描述 投票:-1回答:1

假设我在.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 ou 3dcountour类型中绘制它的好方法吗?

arrays numpy matplotlib matrix scientific-computing
1个回答
0
投票

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

要获得您想要的值,您可以获取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()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.