2012-02-02 74 views
2

我有一個非常大量的數據需要繪圖,它被存儲在3列作爲xyz數據。我需要將列數據轉換爲網格,所以我可以在matplotlib中用contourf輕鬆地繪製它,我想知道是否有一個函數可以做到這一點,因爲我自己編寫的代碼非常慢?列xyz數據到網格繪圖

x y z 

1 1 10 

1 2 12 

2 1 14 

2 2 16 

到這樣的網格:

10 12 

14 16 

回答

2

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開始。

+0

如果前兩列不包含連續的整數或者根本沒有整數? – balu 2014-11-12 13:19:02

+0

找到答案:https://stackoverflow.com/a/15120881/36253 – balu 2014-11-12 15:40:31

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 

注意,這將與一個異常結束時的文件中的所有內容都已經被處理(但所有的值仍將被打印)。爲了避免這種情況,與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] 

希望這有助於