gpt4 book ai didi

python - 比较不同大小的 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:50:52 24 4
gpt4 key购买 nike

我有两个带有 xy 坐标的点数组:

basic_pts = np.array([[0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [0, 2]])
new_pts = np.array([[2, 2], [2, 1], [0.5, 0.5], [1.5, 0.5]])

作为结果,我只想从数组 new_pts 中获取那些满足 basic_pts 中没有具有更大 x AND y 值的点的点。所以结果是

res_pts = np.array([[2, 2], [2, 1], [1.5, 0.5]])

我有一个可行的解决方案,但由于使用列表理解,它不适合更大数量的数据。

x_cond = ([basic_pts[:, 0] > x for x in new_pts[:, 1]])
y_cond = ([basic_pts[:, 1] > y for y in new_pts[:, 1]])
xy_cond_ = np.logical_and(x_cond, y_cond)
xy_cond = np.swapaxes(xy_cond_, 0, 1)
mask = np.invert(np.logical_or.reduce(xy_cond))
res_pts = new_pts[mask]

是否有更好的方法来仅使用 numpy 而无需列表理解来解决此问题?

最佳答案

您可以使用NumPy broadcasting -

# Get xy_cond equivalent after extending dimensions of basic_pts to a 2D array
# version by "pushing" separately col-0 and col-1 to axis=0 and creating a
# singleton dimension at axis=1.
# Compare these two extended versions with col-1 of new_pts.
xyc = (basic_pts[:,0,None] > new_pts[:,1]) & (basic_pts[:,1,None] > new_pts[:,1])

# Create mask equivalent and index into new_pts to get selective rows from it
mask = ~(xyc).any(0)
res_pts_out = new_pts[mask]

关于python - 比较不同大小的 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849300/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com