在Python中将整数数组转换为二进制数组

在Python中将整数数组转换为二进制数组

问题描述:

我正在尝试使用python 2.7将具有整数的数组转换为二进制.

I am trying to convert an array with integers to binary, using python 2.7.

我的代码的简化版本如下:

A simplified version of my code is the following:

 #!/usr/bin/python
 import numpy as np

 a=np.array([6,1,5,0,2])
 b=np.array(np.zeros((5)))

for i in range(10):
    b[i]=bin(int(a[i])).zfill(8)

代码给我错误消息:

b [i] = bin(int(a [i])).zfill(8) ValueError:无效的float()文字:0000b110

b[i]=bin(int(a[i])).zfill(8) ValueError: invalid literal for float(): 0000b110

我的代码有什么问题? 还有另一种方法吗? 原始代码是一个更大的二维数组项目的一部分.

What is wrong with my code? Is there another way to do this? The original code is part of a much greater project with 2 dimensional arrays.

p.s我是Python的相对新手

p.s I'm a relative novice to Python

Numpy尝试将您的二进制数字转换为float,不同之处在于您的数字包含无法解释的b;此字符是通过bin函数添加的,例如. bin(2)0b10.您应该像这样在zfill之前删除此b字符,方法是使用切片"来删除前2个字符:

Numpy attempts to convert your binary number to a float, except that your number contains a b which can't be interpreted; this character was added by the bin function, eg. bin(2) is 0b10. You should remove this b character before your zfill like this by using a "slice" to remove the first 2 characters:

b[i]=bin(int(a[i]))[2:].zfill(8)