Summing one array in terms of another - python
Question: I have two corresponding 2D arrays, one of velocity, one of intensity. The
values of intensity match each of the velocity elements.

I have created another 1d array that that goes from min to max velocity in
even bin widths.

How would I sum the intensity values from my 2d array which correspond to my
velocity bins in my 1d array.

For example: if I have I = 5 corresponding to velocity = 101km/s, then this is
added to the bin 100 - 105 km/s.

Here's my input:

    
    
    rad = np.linspace(0, 3, 100) # polar coordinates
    phi = np.linspace(0, np.pi, 100)
    
    r, theta = np.meshgrid(rad, phi) # 2d arrays of r and theta coordinates
    
    V0 = 225 # Velocity function w/ constants.
    rpe = 0.149
    alpha = 0.003
    
    Vr = V0 * (1 - np.exp(-r / rpe)) * (1 + (alpha * np.abs(r) / rpe)) # returns 100x100 array of Velocities.
    
    Vlos = Vr * np.cos(theta)# Line of sight velocity assuming the observer is in the plane of the polar disk.
    
    a = (r**2) # intensity as a function of radius
    b = (r**2 / 0.23)
    I = (3.* np.exp(-1. * a)) - (1.8 * np.exp(-1. * b))
    

I wish to first create velocity bins from Vmin to Vmax and then sum the
intensities over each bin.

My desired out put would be something along the lines of

    
    
    V_bins = [0, 5, 10,... Vlos.max()]
    
    I_sum = [1.4, 1.1, 1.8, ... 1.2]
    
    plot(V_bins, I_sum)
    

EDIT: I have come up with temporary solution but perhaps there is a more
elegant/efficient method of achieving it?

The two array Vlos and I are both 100 by 100 matrices.

    
    
    Vlos = array([[ 0., 8.9, 17.44, ..., 238.5],...,
    [-0., -8.9, -17.44, ..., -238.5]])
    
    I = random.random((100, 100))
    
    
    
    V = np.arange(Vlos.min(), Vlos.max()+5, 5)
    
    bins = np.zeros(len(V))
    
    for i in range(0, len(V)-1):
        for j in range(0, len(Vlos)): # horizontal coordinate in matrix
            for k in range(0, len(Vlos[0])): # vert coordinate
    
                if Vlos[j,k] >= V[i]and Vlos[j,k] < V[i+1]:
                    bins[i] = bins[i] + I[j,k]
    

The result is plotted below. The overall shape in the histogram is to be
expected, however I don't understand the spike in the curve at V = 0. As far
as I can tell this isn't there in the data which leads me to question my
method.

![I don't expect the spike at zero and I would expect a smoother
curve](http://i.stack.imgur.com/ddtsi.png)

Any further help would be appreciated.


Answer: 
    import numpy as np
    bins = np.arange(100,120,5)
    velocities = np.array([101, 111, 102, 112])
    intensities = np.array([1,2,3,4])
    h = np.histogram(velocities, bins, weights=intensities)
    print h
    

Output:

    
    
    (array([4, 0, 6]), array([100, 105, 110, 115]))
    

