【问题标题】:How to print numpy array in binary representation mode如何以二进制表示模式打印numpy数组
【发布时间】:2014-06-01 05:25:47
【问题描述】:

我有一个以下 numpy 数组

a = np.array([[1,2,3,4 ,11, 12,13,14,21,22,23,24,31,32,33,34 ]], dtype=uint8)

当我打印 a 时,我得到以下输出

[[ 1  2  3  4 11 12 13 14 21 22 23 24 31 32 33 34]]

我怎样才能得到二进制表示的输出?

例如

[[ 00000001  00000010  00000011  00000100 ...]]

【问题讨论】:

    标签: python numpy binary


    【解决方案1】:

    这个怎么样?

    a = np.array([[1,2,3,4 ,11, 12,13,14,21,22,23,24,31,32,33,34 ]], dtype=uint8)
    print [bin(n) for n in a[0]]
    

    使用 numpy 的 unpackbits 也可以。

    A=np.unpackbits(a, axis=0).T
    print [''.join(map(str,a)) for a in A]
    

    【讨论】:

    • 第二个抛出“TypeError: argument 2 to map() must support iteration”
    • 我认为你的数组不是二维的。在您的问题中,您使用两个括号[[]]
    【解决方案2】:

    这会根据您的要求提供

    [bin(x)[2:].zfill(8) for x in a]
    

    输出

    ['00000001', '00000010', '00000011']
    

    【讨论】:

    • 这很好用。谢谢.. 使用矢量化需要相似的时间。
    • 请把它打勾..并记下:)
    【解决方案3】:

    试试这个。

    np.array(map(bin, a.flatten())).reshape(a.shape)
    

    【讨论】:

    • 这是迄今为止最快的解决方案
    • 这在 Python 3 和 numpy 1.21.5 上给出了ValueError: cannot reshape array of size 1 into shape (1,16)
    • @MichaelHerrmann 您可能对np.unpackbits(a).reshape(*a.shape,8) 感兴趣。 8 用于 uint8。替换为您的 dtype 中的位数。
    【解决方案4】:

    您可以使用numpy.binary_repr

    它将一个数字作为输入,并将其二进制表示形式作为字符串返回。您可以将此函数向量化,以便它可以将数组作为输入:

    np.vectorize(np.binary_repr)(a, width=8)
    

    【讨论】:

      【解决方案5】:

      对于 uint8,您可以使用内置的 numpy 函数 unpackbits。 (正如@ysakamoto 所提到的) 首先重塑数组,使其为 1 列宽。 之后使用 unpackbits,如下所述。

      a = numpy.array([[1,2,3,4 ,11, 12,13,14,21,22,23,24,31,32,33,34 ]], dtype="uint8")
      print(numpy.unpackbits(a.reshape(-1,1), axis=1))
      

      输出:

      [[0, 0, 0, 0, 0, 0, 0, 1],
      [0, 0, 0, 0, 0, 0, 1, 0],
      [0, 0, 0, 0, 0, 0, 1, 1],
      [0, 0, 0, 0, 0, 1, 0, 0],
      [0, 0, 0, 0, 1, 0, 1, 1],
      [0, 0, 0, 0, 1, 1, 0, 0],
      [0, 0, 0, 0, 1, 1, 0, 1],
      [0, 0, 0, 0, 1, 1, 1, 0],
      [0, 0, 0, 1, 0, 1, 0, 1],
      [0, 0, 0, 1, 0, 1, 1, 0],
      [0, 0, 0, 1, 0, 1, 1, 1],
      [0, 0, 0, 1, 1, 0, 0, 0],
      [0, 0, 0, 1, 1, 1, 1, 1],
      [0, 0, 1, 0, 0, 0, 0, 0],
      [0, 0, 1, 0, 0, 0, 0, 1],
      [0, 0, 1, 0, 0, 0, 1, 0]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-04
        • 1970-01-01
        • 2020-05-09
        • 1970-01-01
        • 2018-06-15
        • 2011-06-14
        • 2023-03-03
        • 2018-10-11
        相关资源
        最近更新 更多