如何以二进制表示方式打印numpy数组

4

我有一个如下的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 ...]]
5个回答

5

您可以使用numpy.binary_repr

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

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

啊,我真傻。np.vectorize。谢谢分享! - Abe Hoffman

2
这个可以按照您的要求提供。
[bin(x)[2:].zfill(8) for x in a]

输出
['00000001', '00000010', '00000011']

这个完美地运作了。谢谢。它花费的时间与使用向量化相似。 - user3543783
请让它运行起来,并点个赞 :) - sundar nataraj

2

试一下这个。

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

到目前为止,这是最快的解决方案。 - user3543783
1
在Python 3和numpy 1.21.5上运行会出现“ValueError: cannot reshape array of size 1 into shape (1,16)”错误。 - Michael Herrmann
1
@MichaelHerrmann 你可能会对 np.unpackbits(a).reshape(*a.shape,8) 感兴趣。这里的 8 是指 uint8。请将其替换为您的 dtype 中的位数。 - evn

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”错误。 - user3543783
我认为你的数组不是二维的。在你的问题中,你使用了两个方括号 [[]] - ysakamoto

1

对于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]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接