将numpy整数数组转换为12位二进制

时间:2016-09-17 13:31:08

标签: python arrays python-3.x numpy

我需要以数组格式将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

1 个答案:

答案 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']