有没有相当于MATLAB的vct2mtx的Python?

时间:2018-04-19 16:54:57

标签: python numpy matrix

我有一个点(纬度和经度)列表以及这些点的相应值列表。现在我想从中制作一个2D网格。虽然直接在分类的经度和纬度上循环来创建2D网格,但我想知道是否有一个有效的Python函数(可能在numpy?)

import numpy as np
lats = [1,2,3] 
lons=[4,5,6] 
values=[7,8,9]

def vec2mtx(lats, lons, values):
    Z = np.zeros((len(set(lats)),len(set(lons))))
    Z.fill(-9999) # no data value
    lats_grid = np.zeros((len(set(lats)),len(set(lons))))
    lons_grid = np.zeros((len(set(lats)),len(set(lons))))
    search_sorted_lats = np.searchsorted(np.sort(list(set(lats))), lats)
    search_sorted_lons = np.searchsorted(np.sort(list(set(lons))), lons)
    Z[(search_sorted_lats, search_sorted_lons)] = values
    lats_grid[(search_sorted_lats, search_sorted_lons)] = lats
    lons_grid[(search_sorted_lats, search_sorted_lons)] = lons
    Z = np.flipud(Z)
    return lats_grid, lons_grid, Z

lats_grid, lons_grid, Z = vec2mtx(lats, lons, values)

What Z looks like

这段代码完成了我需要做的事情,但这似乎有太多的线条,应该像numpy中的一个衬垫?

1 个答案:

答案 0 :(得分:1)

该片段根据Mad Physicist的推荐进行了更新。也许其他人认为这很有用:

import numpy as np
lats = [1,2,3] 
lons=[4,5,6] 
values=[7,8,9]

def vec2mtx(lats, lons, values):
    ''' Convert vectors of lat,lon locations and values to 2D grid'''
    Z = np.zeros((len(set(lats)),len(set(lons))))
    Z.fill(-9999) # no data value
    lat_set = np.unique(lats); lons_set = np.unique(lons)
    lats_grid = np.zeros((len(lats_set),len(lons_set)))
    lons_grid = np.zeros((len(lats_set),len(lons_set)))
    search_sorted_lats = np.searchsorted(np.sort(lats_set), lats)
    search_sorted_lons = np.searchsorted(np.sort(lons_set), lons)
    Z[(search_sorted_lats, search_sorted_lons)] = values
    lats_grid[(search_sorted_lats, search_sorted_lons)] = lats
    lons_grid[(search_sorted_lats, search_sorted_lons)] = lons
    Z = np.flipud(Z)
    return lats_grid, lons_grid, Z

lats_grid, lons_grid, Z = vec2mtx(lats, lons, values)