使用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