numpy矢量化方法来计算整数数组中的非零位 [英] numpy vectorized way to count non-zero bits in array of integers
本文介绍了numpy矢量化方法来计算整数数组中的非零位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个整数数组:
[int1, int2, ..., intn]
我想计算这些整数的二进制表示中有多少非零位.
I want to count how many non-zero bits are in the binary representation of these integers.
例如:
bin(123) -> 0b1111011, there are 6 non-zero bits
当然我可以遍历整数列表,使用 bin()
和 count('1')
函数,但我正在寻找向量化的方法
Of course I can loop over list of integers, use bin()
and count('1')
functions, but I'm looking for vectorized way to do it.
推荐答案
假设你的数组是 a
,你可以简单地做:
Assuming your array is a
, you can simply do:
np.unpackbits(a.view('uint8')).sum()
示例:
a = np.array([123, 44], dtype=np.uint8)
#bin(a) is [0b1111011, 0b101100]
np.unpackbits(a.view('uint8')).sum()
#9
比较使用benchit
:
#@Ehsan's solution
def m1(a):
return np.unpackbits(a.view('uint8')).sum()
#@Valdi_Bo's solution
def m2(a):
return sum([ bin(n).count('1') for n in a ])
in_ = [np.random.randint(100000,size=(n)) for n in [10,100,1000,10000,100000]]
m1 明显更快.
这篇关于numpy矢量化方法来计算整数数组中的非零位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文