[Numpy-discussion] need a better way to fill a grid

John washakie at gmail.com
Mon Jan 24 08:53:29 EST 2011


I'm trying to cycle over some vectors (lat,lon,emissions) of
irregularly spaced lat/lon spots, and values. I need to sum the values
each contributing to grid on a regular lat lon grid.

This is what I have presently, but it is too slow. Is there a more
efficient way to do this? I would prefer not to create an external
module (f2py, cython) unless there is really no way to make this more
efficient... it's the looping through the grid I guess that takes so


    def grid_emissions(lon,lat,emissions,grid.dx, grid.dy,
grid.outlat0, grid.outlon0, grid.nxmax, grid.nymax):
        """ sample the emissions into a grid to fold into model output

        dx = grid.dxout
        dy = grid.dyout

        # Generate a regular grid to fill with the sum of emissions
        xi = np.linspace(grid.outlon0,
grid.outlon0+(grid.nxmax*grid.d), grid.nxmax)
        yi = np.linspace(grid.outlat0,
grid.outlat0+(grid.nymax*grid.dy), grid.nymax)

        X, Y = np.meshgrid(yi, xi)
        Z = np.zeros(X.shape)

        for i,x in enumerate(xi):
            for j,y in enumerate(yi):
                Z[i,j] = np.sum( emissions[\
                         np.where(((lat>y-dy) & (lat<y+dy)) &
((lon>x-dx) & (lon<x+dx)))[0]])

        return Z

More information about the NumPy-Discussion mailing list