使用Numpy在特定軸上將uint8陣列的元素解包到二進位制輸出陣列中
要將uint8陣列的元素解包到二進位制輸出陣列中,請在Python Numpy中使用**numpy.unpackbits()**方法。結果為二進位制值(0或1)。軸是進行位元解包的維度。軸使用“axis”引數設定。
輸入陣列的每個元素都表示一個位欄位,應將其解包到二進位制輸出陣列中。輸出陣列的形狀要麼是一維的(如果axis為None),要麼與輸入陣列的形狀相同,並在指定的軸上進行解包。
軸是進行位元解包的維度。None表示解包扁平化陣列。“count”引數是沿軸解包的元素數量,作為撤消對非8的倍數大小進行打包的效果的一種方式。非負數表示僅解包count個位元。負數表示從末尾修剪掉這麼多位元。None表示解包整個陣列(預設值)。大於可用位元數的計數將向輸出新增零填充。負計數不得超過可用位元數。
“order”是返回位元的順序。“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()方法。軸使用“axis”引數設定 -
res = np.unpackbits(arr, axis = 1)
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
res = np.unpackbits(arr, axis = 1)
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 1 1 0 0 0 0 1 0 0 1 1] [0 0 0 1 1 0 1 1 0 0 1 0 0 0 1 1]]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP