Python NumPy 'Expected an input array of unsigned byte data type'

标签 python numpy binary

我想生成特定范围内的所有二进制数,目前我的代码是:

int2binary = {}
largest_number = pow(2,16)
binary = np.unpackbits(np.array([range(largest_number)],dtype=np.uint16).T,axis=1)

由于生成的数字将高于 8 位二进制数可以显示的数字,我已将 dtype 从 np.uint8(有效)更改为 np.uint16 然后返回错误:

binary = np.unpackbits(np.array([range(largest_number)],dtype=np.uint16).T,axis=1)
TypeError: Expected an input array of unsigned byte data type

我该如何修复这个错误?我在 NumpPy 网站上查看了它们的数据类型,uint16 就在那里,所以我不确定为什么这不起作用。

更新

使用 Abhisek Roy 的回答,错误不再存在。但是我忘了添加代码的导入部分,它给出了一个新错误:

int2binary[i] = b[i]
IndexError: index 1 is out of bounds for axis 0 with size 1

对于循环:

for i in range(largest_number):
    int2binary[i] = b[i]

最佳答案

我猜这就是你想要的。跑这个。有用。检查并告诉。

import numpy as np
int2binary = {}
largest_number = pow(2,16)
a=(np.array([range(largest_number)],dtype=np.uint8))
b = np.unpackbits(a, axis=1)
for row in b:
    x=row
for i in range(len(x)):
    int2binary[(i)] = x[i]
print(int2binary)

关于Python NumPy 'Expected an input array of unsigned byte data type',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48912471/

相关文章:

python - 在 opencv python 中实现光流时选择我自己的点而不是角点

java - CodeSprint 2 的补码挑战运行得太慢

python - 联立方程求解器,4 个方程 4 个未知数

python - 最大化 keras 模型的 MSE

python - numpy group by,返回按结果排序的原始索引

python - 使用 NumPy 计算平均分数时出错 : 'ufunc add' did not contain a loop

linux - Linux 中 .bin 文件的 header 内容

c++ - 如何在位级别上进行操作?

python - 对 1000 万对 1x20 向量执行余弦相似度的最快方法

python - 如何编写与使用它的类具有相同导入的装饰器?