我有一个非常大量的数据需要绘图,它被存储在3列作为xyz数据。我需要将列数据转换为网格,所以我可以在matplotlib中用contourf轻松地绘制它,我想知道是否有一个函数可以做到这一点,因为我自己编写的代码非常慢?列xyz数据到网格绘图
即
x y z
1 1 10
1 2 12
2 1 14
2 2 16
到这样的网格:
10 12
14 16
我有一个非常大量的数据需要绘图,它被存储在3列作为xyz数据。我需要将列数据转换为网格,所以我可以在matplotlib中用contourf轻松地绘制它,我想知道是否有一个函数可以做到这一点,因为我自己编写的代码非常慢?列xyz数据到网格绘图
即
x y z
1 1 10
1 2 12
2 1 14
2 2 16
到这样的网格:
10 12
14 16
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开始。
假设您的数据包含在data.txt
中。以下代码将按正确的顺序打印出所需的数据部分。
假设data.txt
具有连续行x
和y
坐标:
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
注意,这将与一个异常结束时的文件中的所有内容都已经被处理(但所有的值仍将被打印)。为了避免这种情况,与with open(filepath) as f:
但是更换f = open(filepath)
,如果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]
希望这有助于
如果前两列不包含连续的整数或者根本没有整数? – balu 2014-11-12 13:19:02
找到答案:https://stackoverflow.com/a/15120881/36253 – balu 2014-11-12 15:40:31