[英]How can I convert a numpy to a binary (size 8 bits)
I am searching for a dynamic way to perform a numpy convert (integer to binary).我正在寻找一种动态方式来执行 numpy 转换(整数到二进制)。
I tried to use the 'astype' way but it didn't work out.我尝试使用“astype”方式,但没有成功。
I got a 3-dim matrix like that one:我得到了一个这样的 3-dim 矩阵:
x = np.array([[[1, 2, 44],[1,5,3]],[[7, 88, 12],[1,15,60]]])
I would like to convert each value of x to its binary form (max size of 8 bits) for example, if x includes 6 it will be converted to '00000110'.我想将 x 的每个值转换为其二进制形式(最大大小为 8 位),例如,如果 x 包含 6,它将被转换为“00000110”。
This is a reference for how to convert integer to binary as I need:这是有关如何根据需要将整数转换为二进制的参考:
Converting integer to binary in python 在python中将整数转换为二进制
Is this what you are looking for?这是你想要的?
vfunc = np.vectorize(lambda i: '{0:08b}'.format(i))
x_bin = vfunc(x)
Output of print(x_bin)
: print(x_bin)
输出:
[[['00000001' '00000010' '00101100']
['00000001' '00000101' '00000011']]
[['00000111' '01011000' '00001100']
['00000001' '00001111' '00111100']]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.