numpy boolean array with 1 bit entries

前端 未结 3 1017
灰色年华
灰色年华 2020-12-29 19:24

Is there a way in numpy to create an array of booleans that uses just 1 bit for each entry?

The standard np.bool type is 1 byte, but this way I use 8 ti

3条回答
  •  离开以前
    2020-12-29 19:42

    To do this you can use numpy's native packbits and unpackbits. The first function is straight-forward to use, but to reconstruct you will need additional manipulations. Here is an example:

    import numpy as np
    # original boolean array
    A1 = np.array([
        [0, 1, 1, 0, 1],
        [0, 0, 1, 1, 1],
        [1, 1, 1, 1, 1],
    ], dtype=np.bool)
    
    # packed data
    A2 = np.packbits(A1, axis=None)
    
    # checking the size
    print(len(A1.tostring())) # 15 bytes
    print(len(A2.tostring())) #  2 bytes (ceil(15/8))
    
    # reconstructing from packed data. You need to resize and reshape
    A3 = np.unpackbits(A2, axis=None)[:A1.size].reshape(A1.shape).astype(np.bool)
    
    # and the arrays are equal
    print(np.array_equal(A1, A3)) # True
    

提交回复
热议问题