使用Numpy將uint8陣列的元素解包到二進位制輸出陣列中
要將uint8陣列的元素解包到二進位制輸出陣列中,請使用Python Numpy中的**numpy.unpackbits()**方法。結果是二進位制值(0或1)。
輸入陣列的每個元素代表一個位欄位,應該將其解包到二進位制輸出陣列中。輸出陣列的形狀可以是一維的(如果axis為None),也可以與輸入陣列的形狀相同,沿著指定的axis進行解包。
axis是進行位解包的維度。None表示解包扁平化的陣列。count引數是沿著axis解包的元素個數,作為撤銷非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()方法。結果是二進位制值(0或1):
res = np.unpackbits(arr)
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).
res = np.unpackbits(arr)
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]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP