Search code examples
python-3.xnumpyhistograminterpolationhistogram2d

How to convert edge-values of a 3d histogram into mid-point values of the histogram?


If hist, (x, y, z) = numpy.histogramdd() gives you the histogram values at positions (x, y, z) corresponding to the edges of the bins for a three-dimensional function, how one can calculate (interpolate) the histogram values at midpoints namely (x+d/2, y+d/2, z+d/2) where d is the fixed size of bins in all three directions?


Solution

  • Actually, np.histogramdd gives you the bin boundaries in x, y, z, but the counts are "at the midpoints", not the boundaries (strictly speaking they are neither, they are over d x d x d cubes centered at the midpoints).

    If---for some reason---you have values at boundaries and want to interpolate and if you are ok with linear interpolation:

    np.lib.stride_tricks.as_strided(hist, (2, 2, 2, *map((-1).__add__, hist.shape)), 2 * hist.strides).mean(axis=(0, 1, 2))
    

    This simply takes the average of the 8 nearest neighbors.