NumPy packbits() 函式



NumPy 的packbits()函式用於將二進位制值陣列的元素打包到 uint8 陣列中的位中。此函式將二進位制值的陣列(即 0 和 1)壓縮成一個 8 位無符號整數陣列,其中結果 uint8 陣列中的每個位都表示輸入陣列中的一個元素。

在此函式中,我們可以沿指定軸或在扁平化的輸入陣列上進行操作。在處理大型二進位制資料陣列時,它對於減少記憶體使用特別有用。

語法

以下是 Numpy packbits() 函式的語法:

numpy.packbits(a, /, axis=None, bitorder='big')

引數

以下是 Numpy packbits() 函式的引數:

  • a(array_like): 輸入的二進位制值陣列。
  • axis: 此引數是要打包位的軸。如果為 None,則陣列會被展平。
  • bitorder: 打包表示中的位順序,可以是“big”或“little”。

返回值

此函式返回一個包含打包位元組的uint8型別陣列。

示例 1

以下是 Numpy packbits() 函式的基本示例,其中將 1D 位陣列打包到位元組陣列中:

import numpy as np

# Define the input array of bits (0s and 1s)
bits = np.array([1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1], dtype=np.uint8)

# Pack the bits into bytes
packed = np.packbits(bits)
print(packed)    

以下是packbits()函式的輸出:

[178 229]

示例 2

在 NumPy 中沿預設軸打包 2D 陣列涉及將陣列每行中的二進位制值 0 和 1 轉換為更緊湊的表示形式,例如位元組。

packbits()函式的預設軸為 -1,它指的是最後一個軸,對於 2D 陣列通常是列。以下是一個示例:

import numpy as np

# Define a 2D array of bits
bit_array = np.array([[0, 1, 1, 0, 0, 1, 1, 1], 
                      [1, 0, 1, 1, 0, 0, 0, 0]], dtype=np.uint8)

# Pack the bits into bytes
packed_array = np.packbits(bit_array)

print("Original bit array:\n", bit_array)
print("Packed array:", packed_array)

以下是上述示例的輸出:

Original bit array:
 [[0 1 1 0 0 1 1 1]
 [1 0 1 1 0 0 0 0]]
Packed array: [103 176]

示例 3

以下示例顯示了packbits()函式如何在 3D 陣列上工作:

import numpy as np

# Create a 3D array
arr = np.array([[[1, 0, 1], [0, 1, 0]], [[1, 1, 0], [0, 0, 1]], [[1, 1, 0], [0, 0, 1]]])

# Displaying our array
print("Array...")
print(arr)

# Get the datatype
print("Array datatype...", arr.dtype)

# Get the dimensions of the Array
print("Array Dimensions...", arr.ndim)

# Get the shape of the Array
print("Our Array Shape...", arr.shape)

# Get the number of elements of the Array
print("Elements in the Array...", arr.size)

# To pack the elements of a binary-valued array into bits in a uint8 array, use the numpy.packbits() method in Python Numpy
# The result is padded to full bytes by inserting zero bits at the end
res = np.packbits(arr)
print("Result...", res)  

以下是上述示例的輸出:

Array...
[[[1 0 1]
  [0 1 0]]

 [[1 1 0]
  [0 0 1]]

 [[1 1 0]
  [0 0 1]]]
Array datatype... int64
Array Dimensions... 3
Our Array Shape... (3, 2, 3)
Elements in the Array... 18
Result... [171  28  64]
numpy_binary_operators.htm
廣告