NumPy packbits stores logical entries as bits in unsigned bytes
A sequence of logical entries can occupy one bit per entry when packed into bytes. NumPy packbits performs this conversion, returning unsigned eight-bit integers. Academia Master Trader presents this English lesson for readers in São Tomé and Príncipe, using constructed sequences to explain bit order, padding and the difference between logical packing and preserving arbitrary integer values.
Eight logical entries fill one byte
After import numpy as np, define bits = np.array([1,0,1,0,0,0,0,1],dtype=np.uint8). The call np.packbits(bits) returns [161], with output dtype uint8.
The default bit order is big. Reading the sequence from left to right assigns weights of 128, 64, 32, 16, 8, 4, 2 and 1. The active positions contribute 128 plus 32 plus 1, producing 161.
The output integer represents eight logical positions. It is not their sum, their average or an encoded text character chosen by the function.

Bit order changes the weights
The call np.packbits(bits,bitorder='little') returns [133]. The same logical entries now receive weights starting with one and increasing toward 128.
The active positions contribute 1 plus 4 plus 128, producing 133. The input sequence has not been reversed in place. The rule assigning significance within each output byte has changed.
Bit order is not an axis selection or a choice of row-major versus column-major traversal. Record it separately when a later operation must interpret the stored byte.
Short groups are padded with zero bits
For short = np.array([1,0,1],dtype=np.uint8), the call np.packbits(short) returns [160]. Under big bit order, the three entries occupy the first three bit positions; five trailing zero bits complete the byte.
The original length is therefore useful metadata. The packed byte alone does not distinguish three entries followed by padding from eight meaningful entries ending in five zeros.
Padding happens at the end of each packed sequence. It does not indicate that the source contained extra observations or that missing values were estimated.
An explicit axis keeps other dimensions separate
Define rows = np.array([[1,0,1],[0,1,0]],dtype=np.uint8). The call np.packbits(rows,axis=1) returns [[160],[64]], with shape (2,1). Each row is packed separately and receives its own trailing padding.
With the axis omitted, np.packbits(rows) returns [168]. The input is flattened into six logical positions before a single byte is formed, so its grouping differs from the row-wise result.
Input entries are interpreted logically: zero becomes a zero bit, and a nonzero integer becomes a one bit. For example, np.packbits([0,2,0,-3]) returns [80]. This operation does not preserve the original magnitudes two and minus three.
Continue learning with Academia Master Trader at academiamastertrader.com.br and in Aprenda. Keep the original shape, sequence length, packing axis and bit order alongside packed logical data.