w3resource

NumPy Binary operations: unpackbits() function

numpy.unpackbits() function

The unpackbits() function is used to unpack elements of a uint8 array into a binary-valued output array.
Note: Each element of myarray represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified.

Version: 1.15.0

Syntax:

numpy.unpackbits(myarray, axis=None)

Parameter:

Name Description Required /
Optional
myarray Input array Required
axis The dimension over which bit-unpacking is done. None implies unpacking the flattened array. Optional

Return value:
unpacked [ndarray, uint8 type]
The elements are binary-valued (0 or 1).

Example: numpy.unpackbits() function

>>> import numpy as np
>>> x = np.array([[3], [5], [15]], dtype=np.uint8)
>>> x
array([[ 3],
       [ 5],
       [15]], dtype=uint8)
>>> y = np.unpackbits(x, axis=1)
>>> y
array([[0, 0, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 0, 1, 0, 1],
       [0, 0, 0, 0, 1, 1, 1, 1]], dtype=uint8)

Python Code Editor:

Previous: packbits()
Next: binary_repr()