numpy.packbits() in Python

numpy.packbits() is another function for doing binary operations in numpy.It is used to packs the elements of a binary-valued array into bits in a uint8 array.The result is padded to full bytes by inserting zero bits at the end.

Syntax : numpy.packbits(arr, axis=None)

Parameters :
arr : [array_like] An array of integers or booleans whose elements should be packed to bits.
axis : [ int, optional] The dimension over which bit-packing is done.If none then packing is done in flattened array.

Return : [packed ndarray] Array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements.

Code #1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program explaining
# numpy.packbits() function
  
# importing numpy
import numpy as geek
  
# creating input array using 
# array function
in_arr = geek.array([[[1, 0, 1],
                     [0, 1, 0]],
                     [[1, 1, 0],
                        [0, 0, 1]]])
print ("Input array : ", in_arr) 
  
# packing elements of an array
# using packbits() function
out_arr = geek.packbits(in_arr)
  
print ("Output packed array : ", out_arr)

chevron_right


Output :

Input array :  
[[[1 0 1]
  [0 1 0]]

 [[1 1 0]
  [0 0 1]]]
Output packed array :  [171  16]

 

Code #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program explaining
# numpy.packbits() function
  
# importing numpy
import numpy as geek
  
# creating input array using 
# array function
in_arr = geek.array([[[0, 0, 1],
                     [1, 1, 0]],
                     [[1, 0, 0],
                        [1, 1, 1]]])
print ("Input array : ", in_arr) 
  
# packing elements of an array
# using packbits() function
out_arr = geek.packbits(in_arr, axis = 1)
  
print ("Output packed array along axis 1 : ", out_arr) 

chevron_right


Output :

Input array :  [[[0 0 1]
  [1 1 0]]

 [[1 0 0]
  [1 1 1]]]
Output packed array along axis 1 :  [[[ 64  64 128]]

 [[192  64  64]]]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.