【问题标题】:Python: speed up matrix coordinate mapping through iterationPython:通过迭代加速矩阵坐标映射
【发布时间】:2012-12-31 11:09:50
【问题描述】:

我正试图让这段代码尽可能快地运行,目前效率很低。

我有一个标量数据的 4D 矩阵。 4 个维度对应于纬度、经度、高度和时间。数据存储在一个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的数据点对应于
Lat = 45,Lon = -10.6,Alt = 150,时间 = 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

关于如何加快速度有什么建议吗?
非常感谢!

【问题讨论】:

    标签: python multidimensional-array numpy coordinates


    【解决方案1】:

    如果你将你的列表变成ndarray's,你可以使用如下广播:

    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)
    

    【讨论】:

    • 感谢您的回复!但是,它不起作用……我不断收到:ValueError: array dimensions must agree except for d_0 这似乎是与 axis=-1 相关的问题?
    • 无赖,np.concatenate 不做广播。我修改了代码,这次测试了一下!
    • 我现在收到此错误...ValueError: output operand requires a reduction, but reduction is not enabled 我一直在网上查找,但一无所获!有什么想法吗?
    猜你喜欢
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 2017-01-30
    • 2014-07-24
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多