我需要以数组格式将np数组的整数转换为12位二进制数。这样做最好的方法是什么?
我有点陷入困境,所以任何帮助都会受到赞赏。谢谢!
以下是将整数转换为二进制的内容:
def dec_to_binary(my_int):
"""
Format a number as binary with leading zeros"""
if my_int < 4096:
x= "{0:12b}".format(my_int)
return int(x)
else:
return 111111111111
答案 0 :(得分:1)
轻微更正(将12b
替换为012b
):
def dec_to_binary(my_int):
"""
Format a number as binary with leading zeros
"""
if my_int < 4096:
return "{0:012b}".format(my_int)
else:
return "111111111111"
示例:
In [10]: n_array = np.array([123,234,234,345, 4097])
In [11]: map(dec_to_binary, n_array)
Out[11]:
['000001111011',
'000011101010',
'000011101010',
'000101011001',
'111111111111']