將二值 NumPy 陣列的元素打包到 uint8 陣列中的位中,打包軸為 1
要將二值陣列的元素打包到 uint8 陣列中的位中,請使用 Python NumPy 中的 **numpy.packbits()** 方法。結果透過在末尾插入零位來填充為完整的位元組。軸使用 axis 引數設定。軸是進行位打包的維度。我們已將軸設定為 1。
軸是進行位打包的維度。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() 方法。軸使用 axis 引數設定。軸是進行位打包的維度:
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... [[[128 64 128]] [[128 128 64]] [[128 128 64]]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP