python - numpy boolean 数组内存溢出

标签 python python-3.x numpy boolean

我正在尝试创建一个大型 boolean 数组(用于素数筛)。我首先使用了 Python 列表,但在 limit = 10^9 时,这创建了一个 MemoryError

boolarray = [True] * limit

然后我了解了 Numpy 并了解到它在空间组织方面更好,所以我尝试了

boolarray = np.full(limit, True, dtype = bool)

限制仅略微增加到 10^10,这还不够,因为我需要 10^12。我觉得这很令人惊讶,你只需要一点 boolean 运算,不是吗?任何想法,如何克服这个问题?提前致谢。

最佳答案

让我们先抛开 10^12 位可能不容易装入内存这一事实。如果您更关心内存使用而不是性能,您可以将这些位打包到字节数组中。这是以读/写位时额外计算为代价的(这就是 numpy 将 boolean 值存储为字节的原因)。

import numpy as np


def getbit(bitarray, index):
    i, j = index // 8, index % 8
    x = bitarray[i]
    return x & (1 << j) != 0


def setbit(bitarray, index, value):
    value = bool(value)
    i, j = index // 8, index % 8
    x = bitarray[i]
    bitarray[i] ^= (np.uint(-value) ^ x) & (1 << j)


n = 10**5 // 8
bitarray = np.zeros(n, dtype=np.uint8)  # initialize all bits to 0

print(getbit(bitarray, 19))  # False

setbit(bitarray, 19, True)
print(getbit(bitarray, 19))  # True

setbit(bitarray, 19, False)
print(getbit(bitarray, 19))  # False

关于python - numpy boolean 数组内存溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47391487/

相关文章:

python - 如何在没有列名的情况下更改 pandas 中的列类型?

python - scipy/numpy 中 matlab interp2 样条线的等效项

python - 将数组的值分配给另一个数组的最 Pythonic 方式

python - 顺序处理多线程输出

python - 索引中的 NumPy bool 数组

python - PyDev 中的 PyLint 仅分析最顶层项目目录中的文件

python - 类型错误 : conv2d_v2() got an unexpected keyword argument 'filter

python-3.x - 使用 PyPDF2 检查页面是否垂直?

python-3.x - 如何从 gensim 上的 w2v 获取 tf-id

html - 将自定义标题添加到 Pandas 中的数据框并将其转换为 HTML