解包元素并将解包计数设置为大于 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