# 将2D数据分组为x，y中的重叠圆圈-问答-阿里云开发者社区-阿里云

## 将2D数据分组为x，y中的重叠圆圈

import numpy as np

def inside_circle(x, y, x0, y0, r):

``````return (x - x0)*(x - x0) + (y - y0)*(y - y0) < r*r
``````

x = np.random.random_sample((10000,))
y = np.random.random_sample((10000,))

x0 = np.linspace(min(x),max(x),120)
y0 = np.linspace(min(y),max(y),120)

idx = np.zeros((14400,10000))
r = 2
count = 0

for i in range(0,120):

``````for j in range(0,120):
idx[count,:] = inside_circle(x,y,x0[i],y0[j],r)
count = count + 1``````

Python

• 一码平川MACHEL
2019-07-17 23:26:46

这个使用数组广播，比嵌套的for循环稍快（在我的机器上0.5s vs 0.8s）。在我看来，可读性有所下降。

import numpy as np

x = np.random.random_sample((1, 10000))
y = np.random.random_sample((1, 10000))

x0 = np.reshape(np.linspace(np.min(x),np.max(x),120), (120, 1))
y0 = np.reshape(np.linspace(np.min(y),np.max(y),120), (120, 1))

r = 2

all_xdiffssquared = np.subtract(x, x0)**2
all_ydiffssquared = np.subtract(y, y0)**2

# 3d here means that the array has 3 dimensions. Not the geometry described

all_xdiffssquared_3d = np.reshape(all_xdiffssquared, (120, 10000, 1))
all_ydiffssquared_3d = np.reshape(np.transpose(all_ydiffssquared), (1, 10000, 120))
all_distances_3d = all_xdiffssquared_3d + all_ydiffssquared_3d - r**2
idx = np.signbit(np.reshape(np.moveaxis(all_distances_3d, 1, -1), (14400, 10000)))

0 0
+ 订阅