简体   繁体   English

Python numpy boolean 屏蔽 2d np 阵列

[英]Python numpy boolean masking on 2d np array

I have two 2d numpy arrays X and Y that look like:我有两个 2d numpy arrays X 和 Y 看起来像:

X = np.array([[1,2,3,4],[4,5,6,7],[4,3,2,1],[7,8,9,0]]
            )
Y = np.array([[0,0,0],[1,2,4],[1,1,1], [0,0,0]]
            )

I want to remove all the arrays in Y that are all 0's (ie np.zeros), and all the corresponding arrays at the same index in the X array.我想删除 Y 中所有为 0 的 arrays(即 np.zeros),以及 X 数组中同一索引处的所有相应 arrays。

So, for these two X,Y arrays, I'd like back:所以,对于这两个 X,Y arrays,我想回复:

X = np.array([[4,5,6,7],[4,3,2,1]]
            )
Y = np.array([[1,2,4],[1,1,1]]
            )

X and Y will always have the same length, and X and Y will always be rectangular (ie every array within X will have the same length, and every array within Y will have the same length). X 和 Y 将始终具有相同的长度,并且 X 和 Y 将始终是矩形(即 X 中的每个数组将具有相同的长度,并且 Y 中的每个数组将具有相同的长度)。

I tried using a loop but that doesn't seem to be as effective for large X and Y我尝试使用循环,但这对于大 X 和 Y 似乎没有那么有效

Create a boolean array indicating any non zero element for each row and then filter with boolean array indexing :创建一个 boolean 数组,指示每行的任何非零元素,然后使用boolean 数组索引进行过滤:

any_zero = (Y != 0).any(1)

X[any_zero]
#[[4 5 6 7]
# [4 3 2 1]]

Y[any_zero]    
#[[1 2 4]
# [1 1 1]]

First you will need to get a mask of which rows of Y are all zeros.首先,您需要获取 Y 的哪些行全为零的掩码。 This can be done with the any method and setting the axis to 1这可以使用 any 方法并将轴设置为 1 来完成

Y.any(axis = 1)

Will return array([False, True, True, False]) You can use this array to get which rows you want to return from X and Y将返回array([False, True, True, False])你可以使用这个数组来获取你想要从 X 和 Y 返回的行

X[Y.any(axis = 1)]

will return将返回

array([[4, 5, 6, 7],
       [4, 3, 2, 1]])

and

Y[Y.any(axis = 1)]

will return将返回

array([[1, 2, 4],
       [1, 1, 1]])

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

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