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. If None, the packing will happen in a flattened array. The default value is None.
  • bitorder: It tells the order of bits. The bitorder can either be big or title. the default value for big is bitorder For instance, if the input is 3, 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=None the returned array will be a 1-D array.

Example

# importing numpy library
import numpy as np
# creating 2D array using array function
arr = 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 decimal
print ("\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=-1 as argument values. The axis=-1 means packing will be performed column-wise.

Free Resources