通过布尔掩码数组选择numpy数组的元素

时间:2022-05-15 21:24:14

I guess the answer is close at hand, but I can't see it :-(

我猜答案就在眼前,但我看不到它:-(

I have a boolean mask array of length n:

我有一个长度为n的布尔掩码数组:

a = np.array([True, True, True, False, False])

I have a 2d array with n columns:

我有一个带有n列的2d数组:

b = np.array([[1,2,3,4,5], [1,2,3,4,5]])

I want a new array which contains only the "True"-values, eg:

我想要一个只包含“True”值的新数组,例如:

c = ([[1,2,3], [1,2,3]])

c = a * b does not work because it contains also "0" for the false columns what I don't want

c = a * b不起作用,因为它对于假列而言也包含“0”,这是我不想要的

c = np.delete(b, a, 1) does not work

Any suggestions? Thanks!

有什么建议么?谢谢!

1 个解决方案

#1


36  

You probably want something like this:

你可能想要这样的东西:

>>> a = np.array([True, True, True, False, False])
>>> b = np.array([[1,2,3,4,5], [1,2,3,4,5]])
>>> b[:,a]
array([[1, 2, 3],
       [1, 2, 3]])

Note that for this kind of indexing to work, it needs to be an ndarray, like you were using, not a list, or it'll interpret the False and True as 0 and 1 and give you those columns:

请注意,要使这种索引工作,它需要是一个ndarray,就像你使用的那样,而不是列表,或者它会将False和True解释为0和1,并为你提供这些列:

>>> b[:,[True, True, True, False, False]]   
array([[2, 2, 2, 1, 1],
       [2, 2, 2, 1, 1]])

#1


36  

You probably want something like this:

你可能想要这样的东西:

>>> a = np.array([True, True, True, False, False])
>>> b = np.array([[1,2,3,4,5], [1,2,3,4,5]])
>>> b[:,a]
array([[1, 2, 3],
       [1, 2, 3]])

Note that for this kind of indexing to work, it needs to be an ndarray, like you were using, not a list, or it'll interpret the False and True as 0 and 1 and give you those columns:

请注意,要使这种索引工作,它需要是一个ndarray,就像你使用的那样,而不是列表,或者它会将False和True解释为0和1,并为你提供这些列:

>>> b[:,[True, True, True, False, False]]   
array([[2, 2, 2, 1, 1],
       [2, 2, 2, 1, 1]])