解包元素並將解包計數設定為大於 Numpy 中可用位數
要將 uint8 陣列的元素解包到二進位制值的輸出陣列中,請在 Python Numpy 中使用 **numpy.unpackbits()** 方法。結果為二進位制值(0 或 1)。軸是執行位解包的維度。軸使用“axis”引數設定。要設定要解包的元素數量,請使用“count”引數。
輸入陣列的每個元素都表示一個位欄位,應將其解包到二進位制值的輸出陣列中。輸出陣列的形狀可以是 1-D(如果軸為 None)或與輸入陣列的形狀相同,並且沿指定的軸進行解包。
軸是執行位解包的維度。None 表示解包扁平化陣列。“count”引數是要沿軸解包的元素數量,作為取消打包大小不是 8 的倍數的效果的一種方法。非負數表示僅解包“count”位。負數表示從末尾修剪掉這麼多位。None 表示解包整個陣列(預設值)。大於可用位數的計數將向輸出新增零填充。負計數不得超過可用位數。
順序是返回位的順序。“big”將模擬 bin(val),3 = 0b00000011 ⇒ [0, 0, 0, 0, 0, 0, 1, 1],“little”將反轉順序為 [1, 1, 0, 0, 0, 0, 0, 0]。預設為“big”。
步驟
首先,匯入所需的庫 -
import numpy as np
建立一個二維陣列。我們使用“dtype”引數設定了 uint8 型別 -
arr = np.array([[4, 8], [6, 19], [27, 35]], dtype=np.uint8)
顯示我們的陣列 -
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.unpackbits() 方法。結果為二進位制值(0 或 1)。軸是執行位解包的維度。軸使用“axis”引數設定。要設定要解包的元素數量,請使用“count”引數。我們已將 count 設定為 25,即大於可用位數的計數將向輸出新增零填充 -
res = np.unpackbits(arr, axis = 1, count = 25)
print("
Result...
",res)示例
import numpy as np
# Create a 2d array
# We have set uint8 type using the "dtype" parameter
arr = np.array([[4, 8], [6, 19], [27, 35]], dtype=np.uint8)
# 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 unpack elements of a uint8 array into a binary-valued output array, use the numpy.unpackbits() method in Python Numpy
# The result is binary-valued (0 or 1).
# The axis is the dimension over which bit-unpacking is done.
# The axis is set using the "axis" parameter
# To set the number of element to unpack, use the "count" parameter
# We have set count 25 i.e. Counts larger than the available number of bits will add zero padding to the output
res = np.unpackbits(arr, axis = 1, count = 25)
print("
Result...
",res)輸出
Array... [[ 4 8] [ 6 19] [27 35]] Array datatype... uint8 Array Dimensions... 2 Our Array Shape... (3, 2) Elements in the Array... 6 Result... [[0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 1 1 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0] [0 0 0 1 1 0 1 1 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0]]
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP