I have an array that maps the cells in a game of life. So far I have an int for every single cell. To minimize the amount of reads I want to compress the array to whole 8 cells per 1 integer.
The problem arises when I want to create a bitmap, which expects an array of 0 and 1 like in the previous case.
Is there any quick way in numpy to convert this? I could you a loop for this but there might be a better way.
Example:
[01011100b, 0x0] -> [0, 1, 0, 1, 1, 1, 0 ,0, 0,0,0,0,0,0,0,0]
1 Answer 1
numpy.packbits and numpy.unpackbits are a pretty close match for what you're looking for:
>>> numpy.packbits([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1])
array([225, 184], dtype=uint8)
>>> numpy.unpackbits(array([225, 184], dtype=numpy.uint8))
array([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0], dtype=uint8)
Note that numpy.unpackbits(numpy.packbits(x)) won't have the same length as x if len(x) wasn't a multiple of 8; the end will be padded with zeros.
01011100bstored. Can you get the string representation? If so,list()converts a string into a list of its characters. Is that helpful?hsplit. Wonder if there is a better way without using to stringnumpy.packbitsseems relevant.