python - 如何有效地使用索引数组作为掩码将 numpy 数组转换为 bool 数组?

标签 python arrays performance python-2.7 numpy

我有一个像这样的 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] = False and result[ 1,1,2:] = True
I[1,0] = 0 -> result[1,1,0] = Falseresult[ 1,1,1:] = 真

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

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 循环)?

谢谢!

最佳答案

你只需要在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)

关于python - 如何有效地使用索引数组作为掩码将 numpy 数组转换为 bool 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26582211/

相关文章:

python - 有条件地用 pandas 替换

python - 分发依赖于包的 Python 脚本

python - Pyramid 安全 : how to detect authorization to a view in advance

c++ - 在 C++ 中,如何编写 3 维数组?

python - 如何调试 theano 张量的形状不匹配?

r - 有效地计算列表的出现次数

JAVA Matrix-Vector-Multiplication比C版慢100倍

python - 在 pandas 列中展开词袋(python)

javascript - 如何过滤掉数组之间的匹配项,并添加额外的键/值?

Python网络速度极慢