[英]Convert a numpy bool array to int
I have a numpy array (dtype bool) representing an array of bits.我有一个 numpy 数组(dtype bool)代表一个位数组。 For example, the array np.array([True, False, False], dtype=bool)
represents the number 4 (indeed, bin(4) == 0b100
).例如,数组np.array([True, False, False], dtype=bool)
表示数字 4(实际上, bin(4) == 0b100
)。
I would like to convert the numpy array to an integer ( 4
in the previous example).我想将 numpy 数组转换为 integer(上一个示例中的4
)。
So far I've tried with an iterative approach:到目前为止,我已经尝试过迭代方法:
bits = np.array([True, False, False], dtype=bool)
n = 0
for bit in bits:
n = (n << 1) | bit
This approach does work, but I would prefer something that does not iterate over every element of the array, possibly a numpy built-in method.这种方法确实有效,但我更喜欢不迭代数组的每个元素的方法,可能是 numpy 内置方法。
I also tried using numpy.packbits
(together withnumpy.pad
, because packbits
always automatically pad to the right, and not to the left):我还尝试使用numpy.packbits
(连同numpy.pad
,因为packbits
总是自动向右填充,而不是向左填充):
bits = np.array([True, False, False], dtype=bool)
n = np.packbits(np.pad(bits, ((8 - len(bits) % 8) % 8, 0))).item()
This approach only works for arrays with 8 or less elements.此方法仅适用于具有 8 个或更少元素的 arrays。 Indeed, if you try to use a longer array you end up having multiple results (because apparently packbits
not only pads to the right but also converts every single byte to a number):事实上,如果您尝试使用更长的数组,您最终会得到多个结果(因为显然packbits
不仅向右填充,而且还将每个字节转换为数字):
bits = np.array(
[True, False, False, False, False, False, False, False, False],
dtype=bool,
)
n = np.packbits(np.pad(bits, ((8 - len(bits) % 8) % 8, 0)))
print(n) # this prints [1 0], but I need it to return 256
Expected behavior:预期行为:
np.array([True, True], dtype=bool) --> 3
np.array([True, True, False], dtype=bool) --> 6
np.array([True, False, False, True, True], dtype=bool) --> 19
np.array([True, False, False, False, False,
False, False, True, False, False], dtype=bool) --> 516
Try using numpy.logspace :尝试使用numpy.logspace :
import numpy as np
bits = np.array([True, False, False, False, False, False, False, False, False],dtype=bool,)
bits=bits[::-1]
result = np.sum(np.logspace(0, bits.size-1, num=bits.size, base=2) * bits, dtype=np.int)
This outputs:这输出:
print(result)
256
You can solve this problem by generating the power of two starting from the biggest one (eg. [16, 8, 4, 2, 1]
), and then multiply this by bits
before doing the final sum:您可以通过从最大的一个开始生成两个的幂(例如[16, 8, 4, 2, 1]
)来解决这个问题,然后在进行最终求和之前将其乘以bits
:
powers = 1 << np.arange(bits.size, dtype=np.uint64)[::-1]
result = np.sum(powers * bits)
This is equivalent of doing: 2**n * bits[0] + 2**(n-1) * bits[1] +... + 2**0 * bits[n]
.这相当于做: 2**n * bits[0] + 2**(n-1) * bits[1] +... + 2**0 * bits[n]
。 Note that the final value needs to fit in 64 bits.请注意,最终值需要适合 64 位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.