Python读取X和Y值并分配给Z特定的X Y对

时间:2013-06-27 16:00:00

标签: python contour fromfile

我过去使用python从文件中的数据对创建2D XY图,但现在我需要根据文件中的数据创建等高线图。该文件如下所示:

<Descriptive string>
<some "random" number>
<number of X values:nx>
<Number of Y values:ny>
X1 X2 X3 X4 X5
X6 X7 X8 X9 X10
...
... Xnx
Y1 Y2 Y3 Y4 Y5
Y6 Y7 Y8 Y9 Y10
...
... Yny
Z(X1,Y1) Z(X1,Y2) Z(X1,Y3) Z(X1,Y4) Z(X1,Y5)
Z(X1,Y6) Z(X1,Y7) Z(X1,Y8) Z(X1,Y9) Z(X1,Y10)
...
... 
Z(X1,Yny) Z(X2,Y1) Z(X2,Y3) Z(X2,Y4) Z(X2,Y5)
...
...
Z(X2,Yny) ...
...
...
Z(Xnx,Yny)

到目前为止,我已经能够读取X和Y的值,尽管可能不是最方便的形式,甚至是Z的值,但是我无法正确分配它们以便Z1配合(X1, Y1),Z2与(X1,Y2)一直到Zny与(X1,Yny)一起,并且在末端Znx * ny与(Xnx,Yny)一致。希望这很清楚......到目前为止,这是我所拥有的一段代码:

import numpy as np

# Read from .dat file:
with open("trans_acrolein_ResWVFunAP1R12.dat", "r") as f:
    fl = f.readline()
    xnum = f.readlines()[2]
    ynum = f.readlines()[3]

# Initialize some variables to be lists.
xval = []
yval = []

# Read the values of the number of X and Y values.
for line in xnum:
    px = line.split()
    xval.append(int(px[0]))

for line in ynum:
    py = line.split()
    yval.append(int(py[0]))

linesx = np.ceil(xval/5.0)
linesy = np.ceil(yval/5.0)
linesz = np.ceil((xval*yval)/5.0)

with open("trans_acrolein_ResWVFunAP1R12.dat", "r") as f:
    for line in f:
        x = []
        y = []
        for element in line[4:3+linesx].split():
            x.append(element)
            for element in line[4+linesx:3+linesx+linesy].split():
                y.append(element)

由于我不知道如何连续读取所有元素,我首先使用的方法是计算具有X值的行数,然后是具有Y值的行,最后是具有Z值的行,但我想它效率不高。 如果有人可以帮助我,我将非常感激。 谢谢,

1 个答案:

答案 0 :(得分:1)

我假设N_z_values = N_x_values * N_y_values。如果每行的值相同,那么您应该能够一次解析包含行的所有数据,然后根据N_x_values将其拆分。

例如,如果N_x_values = 27N_y_values = 28并且每行有5个值,则可以执行

import numpy as np
data = []
N_x_values, N_y_values = 0, 0
with open(file_name, 'r') as in_file:
    # skip 2 lines, grab N_X, grab N_Y
    [in_file.next() for _ in range(2)]
    N_x_values = int(in_file.next().strip())
    N_y_values = int(in_file.next().strip())

    for line in in_file:
        line = line.strip().split(' ')
        data.append(map(float, line))

data = np.array(data)
data = data.reshape(np.prod(data.shape))
x_cutoff = N_x_values
y_cutoff = N_y_values
x = data[:x_cutoff]
y = data[x_cutoff:y_cutoff]
z = data[y_cutoff:].reshape(N_x_values, N_y_values)

现在您的值位于表单

的数组中
x.shape = (27, )
y.shape = (28, )
z.shape = (27, 28)

matplotlib.pyplot.contour可以直接获取这些值。例如

import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_suplot(111)
ax.contourf(x, y, z)
ax.colorbar()
plt.show()