守着星空守着你
使用的一个选项numpy是首先在 中添加行mask:take = boolarr.sum(axis=1)#array([2, 1, 3])然后像您一样屏蔽数组:x = arr[boolarr]#array([1, 2, 1, 1, 2, 3])并用于np.split根据np.cumsumof拆分平面数组take(因为函数需要拆分数组的索引):np.split(x, np.cumsum(take)[:-1])[array([1, 2]), array([1]), array([1, 2, 3])]通用解决方案def mask_nd(x, m): ''' Mask a 2D array and preserve the dimension on the resulting array ---------- x: np.array 2D array on which to apply a mask m: np.array 2D boolean mask Returns ------- List of arrays. Each array contains the elements from the rows in x once masked. If no elements in a row are selected the corresponding array will be empty ''' take = m.sum(axis=1) return np.split(x[m], np.cumsum(take)[:-1])例子让我们看一些例子:arr = np.array([[1,2,4], [2,1,1], [1,2,3]])boolarr = np.array([[True, True, False], [False, False, False], [True, True,True]])mask_nd(arr, boolarr)# [array([1, 2]), array([], dtype=int32), array([1, 2, 3])]或者对于以下数组:arr = np.array([[1,2], [2,1]])boolarr = np.array([[True, True], [True, False]])mask_nd(arr, boolarr)# [array([1, 2]), array([2])]