Python 如何用NumPy将整数向量转换成二进制表示的矩阵?

Python 如何用NumPy将整数向量转换成二进制表示的矩阵?,python,numpy,Python,Numpy,假设我有以下数组: import numpy as np I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128]) 我想将数组中的每个项转换为其二进制表示形式 所需输出: [[0 0 0 0 0 0 0 0] [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 1 1 1 1] [0 0 0 1 0 0 0 0] [0 0 1 0 0 0 0 0] [0 1 0 0 0

假设我有以下数组:

import numpy as np
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])
我想将数组中的每个项转换为其二进制表示形式

所需输出:

[[0 0 0 0 0 0 0 0]
 [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 1 1 1 1]
 [0 0 0 1 0 0 0 0]
 [0 0 1 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0]]
# Your array
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])

B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))
最直接的方法是什么?
谢谢

有很多方法可以做到这一点

一种方法:

[[0 0 0 0 0 0 0 0]
 [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 1 1 1 1]
 [0 0 0 1 0 0 0 0]
 [0 0 1 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0]]
# Your array
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])

B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))
您也可以这样做:

[[0 0 0 0 0 0 0 0]
 [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 1 1 1 1]
 [0 0 0 1 0 0 0 0]
 [0 0 1 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [1 0 0 0 0 0 0 0]]
# Your array
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])

B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print(B[:,::-1])
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))
我个人会推荐第一种方法! 干杯

这将为您提供所需的输出,{0:08b}为您提供数字的二进制表示形式,由8位数字组成一个字符串,在第二个列表中,二进制数被拆分为数字,然后将结果转换为numpy数组。

您可以使用bin()函数将整数转换为二进制字符串

可能的解决方案之一是:

[list(bin(num)[2:].zfill(8)) for num in I ]
在这里,我使用列表理解来迭代数组,然后对于数组中的每个数字,我应用bin函数将其转换为二进制字符串。然后我使用zfill(8)在字符串的开头添加零,使其长度为8,这是输出格式所要求的。然后将其键入列表中