2012-12-31 45 views
3

我試圖讓這段代碼儘可能快地運行,而且目前效率很低。Python:通過迭代加快矩陣座標映射

我有一個4D的標量數據矩陣。這四個維度對應於緯度,經度,高度和時間。數據存儲在一個numpy數組中,其形狀是(5,5,30,2)。

在4個不同的列表中我保留每個軸的「映射」,存儲每個索引對應的值。例如,在地圖上的陣列可能看起來像:

mapLatitude = [45.,45.2,45.4,45.6,45.8] 
mapLongitude = [-10.8,-10.6,-10.4,-10.2,-10.] 
mapAltitude = [0,50,100,150,...,1450] 
mapTime = [1345673,1345674] 

這意味着,在數據矩陣,在位置0,1,3,0的數據點對應於
緯度= 45,經度= -10.6, Alt = 150,Time = 1345673.

現在,我需要生成一個新的數組,其中包含數據矩陣中每個點的座標。

到目前爲止,這是我寫的:

import numpy as np 

# data = np.array([<all data>]) 
coordinateMatrix = [ 
    (mapLatitude[index[0]], 
    mapLongitude[index[1]], 
    mapAltitude[index[2]], 
    mapTime[index[3]]) for index in numpy.ndindex(data.shape) ] 

這工作,但需要相當長的時間,尤其是在大小的數據矩陣增加(我需要用一個矩陣使用形狀像(100,100,150,30))。

如果有幫助,我需要生成此座標矩陣將其送到scipy.interpolate.NearestNDInterpolator

關於如何加快速度的建議?
非常感謝!

回答

3

如果你把你的名單到ndarray的,你可以使用廣播如下:

coords = np.zeros((5, 5, 30, 2, 4)) 
coords[..., 0] = np.array(mapLatitude).reshape(5, 1, 1, 1) 
coords[..., 1] = np.array(mapLongitude).reshape(1, 5, 1, 1) 
coords[..., 2] = np.array(mapAltitude).reshape(1, 1, 30, 1) 
coords[..., 3] = np.array(mapTime).reshape(1, 1, 1, 2) 

更多通用輸入這樣的事情應該工作:

def makeCoordinateMatrix(*coords) : 
    dims = len(coords) 
    coords = [np.array(a) for a in coords] 
    shapes = tuple([len(a) for a in coords]) 
    ret = np.zeros(shapes + (dims,)) 
    for j, a in enumerate(coords) : 
     ret[..., j] = a.reshape((len(a),) + (1,) * (dims - j - 1)) 
    return ret 

coordinateMatrix = makeCoordinateMatrix(mapLatitude, mapLongitude, 
             mapAltitude, mapTime) 
+0

感謝您的答覆! 然而,它不工作......我不斷收到:'ValueError:數組維度必須同意,除了d_0' 看來這是一個與軸= -1有關的問題? –

+0

Bummer,'np.concatenate'不會播放。我修改了代碼,並且這次測試它! – Jaime

+0

現在我得到這個錯誤...'ValueError:輸出操作數需要減少,但減少未啓用' 我一直在網上查找,但一無所知!有任何想法嗎? –