通过布尔掩码数组选择numpy数组的元素 [英] Select elements of numpy array via boolean mask array
问题描述
我想答案就在眼前,但是我看不到它: - (
I guess the answer is close at hand, but I can't see it :-(
我有一个长度为n的布尔掩码数组:
I have a boolean mask array of length n:
a = np.array([True, True, True, False, False])
我有一个带有n列的二维数组:
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
不起作用,因为它对于假列而言也包含0我不想要的内容
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!
推荐答案
你可能想要这样的东西:
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]])
请注意,要使这种索引工作,它必须是 ndarray
,就像你一样使用,而不是列表
,或者它将解释 False
和 True
as 0
和 1
并为您提供以下列:
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]])
这篇关于通过布尔掩码数组选择numpy数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!