Use Numpy to generate/restore bitmaps

If you are working on some data system to deal with DAU or something similar,

one convenient data structure is the bitmap

for more detail about what bitmap is, you could have a look at here

following is the snippet of transforming list of ids into bitmaps and back gist:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np
ids = [1, 5, 7, 12]
bitmaps = np.zeros(max(ids) + 1, dtype=np.bool)
bitmaps[ids] = True
bitmaps = np.packbits(bitmaps).tostring()
print(bitmaps)
# b'E\x08'
# could be use as a binary field to be stored in database
origin_ids = np.where(
np.unpackbits(
np.frombuffer(bitmaps,
dtype=np.uint8)))[0].tolist()
print(origin_ids)
# [1, 5, 7, 12]

Zhanzhao Deo Liang wechat
欢迎关注我的个人订阅号: deoXdeo
今天的午餐全赖有你支持!