Select elements of numpy array via boolean mask ar

2019-01-18 01:44发布

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

I have a boolean mask array of length n:

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

I have a 2d array with n columns:

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:

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 = np.delete(b, a, 1) does not work

Any suggestions? Thanks!

2条回答
Melony?
2楼-- · 2019-01-18 02:14

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:

>>> b[:,[True, True, True, False, False]]   
array([[2, 2, 2, 1, 1],
       [2, 2, 2, 1, 1]])
查看更多
我命由我不由天
3楼-- · 2019-01-18 02:18

You can use numpy.ma module and use np.ma.masked_array function to do so.

x = np.array([1, 2, 3, -1, 5])
mx = ma.masked_array(x, mask=[0, 0, 0, 1, 0])

return : masked_array(data=[1, 2, 3, --, 5], mask=[False, False, False, True, False], fill_value=999999)

查看更多
登录 后发表回答