在Numpy ndarray中,如何根据不同维度中的条件删除维度中的元素?
我有:
[[[1 3]
[1 4]]
[[2 6]
[2 8]]
[[3 5]
[3 5]]]我想根据条件x[:,:,1] < 7删除
期望输出([:,1,:]删除):
[[[1 3]
[1 4]]
[[3 5]
[3 5]]]编辑:固定排版
发布于 2020-03-28 01:58:00
作为您想要的输出,您可以在x上过滤axis=0。因此,你可以试试这个方法。
m = (x[:,:,1] < 7).all(1)
x_out = x[m,:,:]或者简单的
x_out = x[m]
Out[70]:
array([[[1, 3],
[1, 4]],
[[3, 5],
[3, 5]]])发布于 2020-03-28 01:19:54
这样做可能会奏效:
x[np.where(np.all(x[..., 1] < 7, axis=1)), ...]收益率
array([[[[1, 3],
[1, 4]],
[[3, 5],
[3, 5]]]])您确实获得了额外的维度,但这很容易删除:
np.squeeze(x[np.where(np.all(x[..., 1] < 7, axis=1)), ...])简单地说,它是如何工作的:
首先是条件:x[..., 1] < 7。
然后测试条件是否对特定轴上的所有元素有效:np.all(x[..., 1] < 7, axis=1)。
然后,使用where来获取索引,而不是一组布尔值:np.where(np.all(x[..., 1] < 7, axis=1))。
并将这些索引插入相关维度:x[np.where(np.all(x[..., 1] < 7, axis=1)), ...]。
https://stackoverflow.com/questions/60896121
复制相似问题