将xyz列数据转换为绘图网格

3 投票
2 回答
4901 浏览
提问于 2025-04-17 12:12

我有一大堆数据需要绘图,这些数据存储在三列中,分别是x、y和z。为了方便用matplotlib中的contourf函数绘图,我需要把这些列的数据转换成一个网格。我在想有没有现成的函数可以做到这一点,因为我自己写的代码运行得非常慢。

也就是说,我想把这样的数据:

x y z

1 1 10

1 2 12

2 1 14

2 2 16

转换成像这样的网格:

10 12

14 16

2 个回答

0

假设你的数据保存在 data.txt 文件里。下面的代码会按照正确的顺序打印出你需要的数据部分。

假设 data.txt 文件里的内容是 xy 坐标,分别在连续的行上:

data.txt
x y z
1 1 10
1 2 12
2 1 14
2 2 16

def extract(filepath):
    f = open(filepath)
    f.readline() # to read out the first line that says "x y z"
    while 1:
        x = f.readline().strip().split()[-1]
        y = f.readline().strip().split()[-1]
        print x, y

需要注意的是,当文件里的所有内容都处理完后,这段代码会出现一个异常(不过所有的值还是会被打印出来)。为了避免这个问题,可以把 f = open(filepath) 改成 with open(filepath) as f:

但是,如果 data.txt 的结构不是这样的,你就需要利用每行的前两个数字:

data.txt
x y z
1 1 10
2 1 14
1 2 12
2 2 16

from collections import defaultdict
def extract(filepath):
    coords = defaultdict(dict)
    f = open(filepath)
    f.readline() # to read out the first line that says "x y z"
    for line in f:
        id, axis, val = map(int, line.strip().split())
        coords[id][axis] = val

    for i in sorted(coords):
        print coords[i][1], coords[i][2]

希望这对你有帮助。

1

numpy在这方面挺聪明的。你可以把每一列的数据读到不同的数组里,然后这样做:

import numpy

idx1 = numpy.array([0, 0, 1, 1])
idx2 = numpy.array([0, 1, 0, 1])
data = numpy.array([10, 12, 14, 16])

grid = numpy.zeros(len(data)/2, 2)
grid[idx1, idx2] = data

>>>grid
array([[ 10.,  12.],
      [ 14.,  16.]])

记住,索引是从0开始的,所以如果你的索引是从1开始的,你需要在每个元素上减去1。

撰写回答