將二值 NumPy 陣列的元素打包到沿負軸的 uint8 陣列中的位中


要在 Python NumPy 中將二值陣列的元素打包到 uint8 陣列中的位中,請使用 **numpy.packbits()** 方法。結果透過在末尾插入零位來填充到完整的位元組。軸使用 axis 引數設定。軸是進行位打包的維度。我們設定了負軸。

軸是進行位打包的維度。None 表示打包扁平化陣列。bitorder 是輸入位的順序。“big”將模擬 bin(val),[0, 0, 0, 0, 0, 0, 1, 1] ⇒ 3 = 0b00000011,“little”將反轉順序,因此 [1, 1, 0, 0, 0, 0, 0, 0] ⇒ 3。預設為“big”。

packbits() 函式返回 uint8 型別的陣列,其元素表示與輸入元素的邏輯值 (0 或非零值) 對應的位。packed 的形狀與輸入具有相同數量的維度。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個 3D 陣列:

arr = np.array([[ [1,0,1], [0,1,0]], [ [1,1,0], [0,0,1]], [ [1, 1, 0],[0, 0, 1] ]])

顯示我們的陣列:

print("Array...
",arr)

獲取資料型別:

print("
Array datatype...
",arr.dtype)

獲取陣列的維度:

print("
Array Dimensions...
",arr.ndim)

獲取陣列的形狀:

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素個數:

print("
Elements in the Array...
",arr.size)

要將二值陣列的元素打包到 uint8 陣列中的位中,請使用 numpy.packbits() 方法。結果透過在末尾插入零位來填充到完整的位元組:

res = np.packbits(arr, axis = -1)
print("
Result...
",res)

示例

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...
",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 # The axis is set using the axis parameter # The axis is the dimension over which bit-packing is done. res = np.packbits(arr, axis = -1) 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...
[[[160]
[ 64]]

[[192]
[ 32]]

[[192]
[ 32]]]

更新於:2022年2月18日

249 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告