繁体   English   中英

如果一个元素小于或大于某个值,如何删除 2D numpy 数组中的列

[英]How to remove columns in 2D numpy array if one element is smaller or larger than a certain value

现在我有一个表示图像坐标像素的二维 numpy 数组

points = [[-1,-2,0,1,2,3,5,8] [-3,-4,0,-3,5,9,2,1]]

每列代表图像中的一个坐标,例如:array[0] = [-1,-3] 表示 x = -1 和 y = -3

现在,我想删除 x 小于 0 && 大于 5 或​​ y 小于 0 && 大于 5 的列

我知道如何删除特定值的元素

#remove x that is less than 0 and more than 5
     x = points[0,:] 
     x = x[np.logical_and(x>=0, x<=5)]

#remove y that is less than 0 and more than 5
     y = points[1,:] 
     y = y[np.logical_and(y>=0,y<=5)]

有没有办法删除与被删除的 x 共享相同索引的 y?(换句话说,当满足 x 删除或 y 删除的条件时删除列)

您可以将list转换为ndarray ,然后创建一个 boolean 掩码并重新分配x , y 嵌套的logical_and意味着您创建了x>=0 and x<=5y>=0 and y<=5的掩码,然后AND运算符确保一旦x[i]删除, y[i]被删除为好

points = [[-1,-2,0,1,2,3,5,8], [-3,-4,0,-3,5,9,2,1]]
x = np.array(points[0,:])
y = np.array(points[1,:])

mask = np.logical_and(np.logical_and(x>=0, x<=5), np.logical_and(y>=0, y<=5))
# mask = array([False, False,  True, False,  True, False,  True, False])

x = x[mask] # x = array([0, 2, 5])
y = y[mask] # y = array([0, 5, 2])

您可以沿轴使用np.compress =1 来获取您需要的点:

np.compress((x>=0) * (x<=5) * (y>=0) * (y<=5), points, axis=1)

array([[0, 2, 5],
       [0, 5, 2]])

我假设xypoints是 numpy 数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM