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

John washakie at gmail.com
Mon Jan 24 09:58:45 EST 2011

```I will try this as well and report back with a timing...

On Mon, Jan 24, 2011 at 3:56 PM, Vincent Schut <schut at sarvision.nl> wrote:
> On 01/24/2011 02:53 PM, John wrote:
>> Hello,
>>
>> 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
>> long.
>
> Use np.histogram2d with weights=emissions, and lat and lon as your x and
> y to histogram. Choose the bins to match your grid, and it will
> effectively sum the emission values for each grid cell.
>
> Vincent.
>
>>
>> Thanks,
>> john
>>
>>
>>
>>      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
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>

--
Configuration
``````````````````````````
Plone 2.5.3-final,
CMF-1.6.4,
Zope (Zope 2.9.7-final, python 2.4.4, linux2),
Python 2.6
PIL 1.1.6
Mailman 2.1.9
Postfix 2.4.5
Procmail v3.22 2001/09/10
Basemap: 1.0
Matplotlib: 1.0.0

```