简体   繁体   English

在python中从文件读取Meshgrid数据

[英]Reading meshgrid data from file in python

I have a file "data.dat" following data: 我有以下数据文件“ data.dat”:

[[0.2 0.3 0.4][0.3 0.2 0.4][0.5 0.3 0.4]]

Now I am reading this data from file as 现在我从文件中读取此数据为

f=open("data.dat","r")
z=f.read()
f.close()

I have x=[1 2 3] & y=[1 2 3] . 我有x=[1 2 3]y=[1 2 3] I made a meshgrid from x & y as 我用xy制作了一个网格

X,Y=plt.meshgrid(x,y)

Now I am trying to do contour plot using 现在我正在尝试使用绘制轮廓图

plt.contourf(X,Y,Z)

But it is showing error as: ValueError: could not convert string to float: [[0.2 0.3 0.4][0.3 0.2 0.4][0.5 0.3 0.4]] 但是它显示错误为:ValueError:无法将字符串转换为float:[[0.2 0.3 0.4] [0.3 0.2 0.4] [0.5 0.3 0.4]]

Any suggestion about how to read Z array as float from file or to write the "data.dat" file in other way? 关于如何从文件中读取Z数组为float或以其他方式写入“ data.dat”文件的任何建议?

You are reading a string from the file and putting that string to Z . 您正在从文件中读取字符串,并将该字符串放入Z But in fact you need two-dimensional array of floats instead of string. 但实际上,您需要浮点数的二维数组而不是字符串。 So you have to parse your string. 因此,您必须解析您的字符串。 It can be done by converting it to JSON like this: 可以通过将其转换为JSON来完成,如下所示:

import json
with open("data.dat") as f:
    z = f.read()
z = z.replace(' ', ', ').replace('][', '], [')
Z = json.loads(z)

the other (and better) way is to use JSON to store your data in a file. 另一种(更好的方法)是使用JSON将数据存储在文件中。

import json    
Z = [[0.2, 0.3, 0.4], [0.3, 0.2, 0.4], [0.5, 0.3, 0.4]]
with open("data.dat", 'w') as f:
    json.dump(Z, f)

You also can try different formats, like CSV. 您还可以尝试其他格式,例如CSV。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM