'Binning 2D data with circles instead of rectangles - from pandas df

I have a dataframe of x, y data and need to bin it into circles. Ie a grid of circles of certain size and spacing centered on some point. So for example some data would be left out after this sampling/binning. How is this possible?

I have tried np.histogram2d and creating masks/broadcasting. The mask was too slow, and I don't seem able to broadcast into a circle. Only to tell if the point is within said grid of circles via this answer: Binning 2D data into overlapping circles in x,y.

If there is a way to input edges or something into histogram2d and make the edges circular please let me know. Cheers



Solution 1:[1]

The only way this can be done is by looping over your points and grid of circles like so:

def inside_circle(x, y, x0, y0, r):
    return (x - x0)*(x - x0) + (y - y0)*(y - y0) < r*r


x_bins = np.linspace(-9, 9, 30)
y_bins = np.linspace(-9, 9, 30)

h = df['upmm']
w = df['anode_entrance']

histo = np.zeros((32,32))

for i in range(0, len(h)):
    for j in range(0, len(x_bins)):
        for k in range(0, len(y_bins)):
            if inside_circle(h[i], w[i], x_bins[j], y_bins[k], 0.01):
                histo[j][k] = histo[j][k] + 1
            
plt.imshow(histo, cmap='hot', interpolation='nearest')
plt.show()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 twoface