【问题标题】:How to efficiently use a index array as a mask to turn a numpy array into a boolean array?如何有效地使用索引数组作为掩码将 numpy 数组转换为布尔数组?
【发布时间】:2014-12-22 07:34:44
【问题描述】:

我有一个这样的 numpy 数组:

>>> I
array([[ 1.,  0.,  2.,  1.,  0.],
       [ 0.,  2.,  1.,  0.,  2.]])

还有一个像这样的数组 A:

>>> A = np.ones((2,5,3))

我想得到以下矩阵:

>>> result
array([[[ False,  False,  True],
        [ False,  True,  True],
        [ False,  False,  False],
        [ False,  False,  True],
        [ False,  True,  True]],

       [[ False,  True,  True],
        [ False,  False,  False],
        [ False,  False,  True],
        [ False,  True,  True],
        [ False,  False,  False]]], dtype=bool)

最好举例说明:
I[0,0] = 1 -> result[0,0,:2] = Falseresult[1,1,2:] = True
I[1,0] = 0 -> result[1,1,0] = Falseresult[1,1,1:] = True

这是我当前的实现(正确):

result = np.empty((A.shape[0], A.shape[1], A.shape[2]))
r = np.arange(A.shape[2])
for i in xrange(A.shape[0]):
    result[i] = r > np.vstack(I[i])

print result.astype(np.bool)

有没有办法以更快的方式实现(避免 for 循环)?

谢谢!

【问题讨论】:

  • 我试图运行你的代码,但它对我不起作用。您能否修改您的问题并使其更清楚?
  • 对不起,我的错。 A 是 (2,5,3) 矩阵。我还添加了一个带有布尔转换的打印

标签: python arrays performance python-2.7 numpy


【解决方案1】:

您只需在I 上添加另一个维度,这样您就可以正确广播r

result = r > I.reshape(I.shape[0],I.shape[1],1)

例如

In [41]: r>I.reshape(2,5,1)
Out[41]: 
array([[[False, False,  True],
        [False,  True,  True],
        [False, False, False],
        [False, False,  True],
        [False,  True,  True]],

       [[False,  True,  True],
        [False, False, False],
        [False, False,  True],
        [False,  True,  True],
        [False, False, False]]], dtype=bool)

【讨论】:

    猜你喜欢
    • 2014-12-20
    • 2014-10-28
    • 2012-01-03
    • 2016-12-10
    • 1970-01-01
    • 2014-07-29
    • 2022-10-18
    • 2020-05-09
    • 2020-02-14
    相关资源
    最近更新 更多