arrays - 如何将一组数据转换为矩阵和向量
问题描述
假设我在一个 .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 类型绘制它的好方法吗?
解决方案
要绘制散点图,您无需对数据执行任何操作。只需按原样绘制那里的列。
要获得您想要的值,您可以获取 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()
推荐阅读
- google-apps-script - 如何以编程方式在 Google 表格中使用仪表盘
- python - 如何使用 Flask WTF 获取 QuerySelectField 当前值
- javascript - ReactJS 和 Node.JS [JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符]
- glsl - 丢弃着色器中的特定面
- r - 将三个数据帧中的列一一组合
- prometheus - 如何解决 promethesus blackbox_exporter 401 错误
- python - 什么是 Django 配置?
- machine-learning - PyTorch 和 Keras 上的 CIFAR-10 测试集分类准确度不同
- python - 对一个小时内落下的单元格进行分组 - Groupby
- java - 如何在反序列化 Pojo 时忽略 JSON 根元素