What is numpy.packbits() in Python?
Overview
The numpy.packbits() method is used to pack a binary-valued array into an uint8 array. It returns a fully padded ndarray with zero at the end, to the full length of an unsigned integer of 8 bits.
Note: The
packbits()method is also used to deal with numbers at the bit level.
Syntax
numpy.packbits(array, /, axis=None, bitorder='big')
Parameters
It takes the following argument values.
array: It can either be an integer or boolean array. The array whose values are going to be packed.axis: This tells the function how to perform packing or in which direction packing will happen. IfNone, the packing will happen in a flattened array. The default value isNone.bitorder: It tells the order of bits. The bitorder can either bebigortitle. the default value forbigisbitorderFor instance, if the input is3, the order will be in both cases as follows:'big': [0 0 0 0 0 0 1 1] =>0x00000011'title': [1 1 0 0 0 0 0 0] =>0x11000000
Return value
It will return a NumPy ndarray of type uint8, which has the following attributes.
- Each value represents bits corresponding to input values.
- Dimensions of the packed array will be the same as the input array.
- If
axis=Nonethe returned array will be a 1-D array.
Example
# importing numpy libraryimport numpy as np# creating 2D array using array functionarr = np.array([[[1, 1, 1],[0, 1, 0]],[[-1, 1, 0],[0, 0, 1]]])print ("Input array : ", arr)# Invoking packbits() function to pack binary array to decimalprint ("\nOutput packed array : ", np.packbits(arr, axis=-1))
Explanation
- Line 4: We create a two-dimensional NumPy array, by invoking
np.array()method. - Line 8: We print the above generated two-dimensional array on the console.
- Line 10: The
np.packbits()method takes the array &axis=-1as argument values. Theaxis=-1means packing will be performed column-wise.