python - numpy矢量化方法来计算整数数组中的非零位

标签 python arrays numpy vectorization

我有一个整数数组:

[int1, int2, ..., intn]
我想计算这些整数的二进制表示中有多少非零位。
例如:
bin(123) -> 0b1111011, there are 6 non-zero bits
当然我可以遍历整数列表,使用 bin()count('1')功能,但我正在寻找矢量化的方式来做到这一点。

最佳答案

假设你的数组是 a ,你可以简单地做:

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 明显更快。
enter image description here

关于python - numpy矢量化方法来计算整数数组中的非零位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63954102/

相关文章:

python - 在 Python 中将二进制列表转为 PNG

javascript - 对象操作javascript,将对象的值添加到对象数组中

c - 排序篮球运动员名字的函数

python - 使用 numpy 向量化检查 Pandas 列中的引用列表

python - 一串 kwargs 到 kwargs

python - 学习 PyGame 的最佳资源?

python "in"类应用程序

javascript - 在 knockout 阵列中搜索重复条目

python - 使用变量 reshape Numpy 中的数组

python - Numpy 会自动检测和使用 GPU 吗?