从几个布尔numpy数组创建"位掩码"

MSe*_*ert 5 python numpy

我正在尝试将几个掩码(布尔数组)转换为带有numpy的位掩码,而理论上的工作原理我觉得我做了太多的操作.

例如,要创建我使用的位掩码:

import numpy as np

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

flag_bits = np.zeros(3, dtype=np.int8)
for idx, flag in enumerate(flags):
    flag_bits += flag.astype(np.int8) << idx  # equivalent to flag * 2 ** idx
Run Code Online (Sandbox Code Playgroud)

这给了我预期的"位掩码":

>>> flag_bits 
array([1, 6, 0], dtype=int8)

>>> [np.binary_repr(bit, width=7) for bit in flag_bits]
['0000001', '0000110', '0000000']
Run Code Online (Sandbox Code Playgroud)

但是我觉得特别是int8flag_bits阵列的投射和添加过于复杂.因此,我想询问是否有任何我错过的NumPy功能可用于创建这样的"位掩码"数组?

注意:我正在调用一个需要这样一个位掩码的外部函数,否则我会坚持使用布尔数组.

Div*_*kar 1

这是一种直接获取字符串位掩码boolean-indexing方法-

out = np.repeat('0000000',3).astype('S7')
out.view('S1').reshape(-1,7)[:,-3:] = np.asarray(flags).astype(int)[::-1].T
Run Code Online (Sandbox Code Playgroud)

样本运行 -

In [41]: flags
Out[41]: 
[array([ True, False, False], dtype=bool),
 array([False,  True, False], dtype=bool),
 array([False,  True, False], dtype=bool)]

In [42]: out = np.repeat('0000000',3).astype('S7')

In [43]: out.view('S1').reshape(-1,7)[:,-3:] = np.asarray(flags).astype(int)[::-1].T

In [44]: out
Out[44]: 
array([b'0000001', b'0000110', b'0000000'], 
      dtype='|S7')
Run Code Online (Sandbox Code Playgroud)

使用与 中详细讨论的相同的矩阵乘法策略@Marat's solution,但使用矢量化缩放数组,它给我们flag_bits-

np.dot(2**np.arange(3),flags)
Run Code Online (Sandbox Code Playgroud)