简体   繁体   English

如何使用 NumPy 将整数向量转换为二进制表示矩阵?

[英]How to convert a vector of integers into a matrix of binary representation with NumPy?

Suppose I have the following array:假设我有以下数组:

import numpy as np
I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])

I would like to convert each item in the array into its binary representation.我想将数组中的每个项目转换为其二进制表示。

Desired output:所需的 output:

[[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]]

Whats the most straight forward way to do this?最直接的方法是什么? Thanks!谢谢!

There are many ways you can accomplish this.有很多方法可以做到这一点。

One way to do it:一种方法:

# 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])

You can also do this:你也可以这样做:

I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)
print(np.unpackbits(I[:, np.newaxis], axis=1))

I personalty would recommend the first method!我个人会推荐第一种方法! Cheers!干杯!

np.array([[int(d) for d in '{0:08b}'.format(el)] for el in I])

This should give you the desired output, {0:08b} gives you the binary representation of your number consisting of 8 digits as a string, in a second list comprehension the binary number is split into digits and then result is converted to a numpy array.这应该为您提供所需的 output,{0:08b} 为您提供由 8 位数字组成的数字的二进制表示作为字符串,在第二个列表理解中,二进制数被拆分为数字,然后将结果转换为 numpy 数组.

You can use bin() function to convert an integer to a binary string.您可以使用 bin() function 将 integer 转换为二进制字符串。

One of the possible solution can be:一种可能的解决方案可以是:

[list(bin(num)[2:].zfill(8)) for num in I ]

Here I am using list comprehension for iterating over the array and then for each number in the array, I am applying bin function to convert it to the binary string.在这里,我使用列表推导来迭代数组,然后对于数组中的每个数字,我应用 bin function 将其转换为二进制字符串。 Then I am using zfill(8) to add zeros at the beginning of the string to make it of length 8, as required by your output format.然后我使用 zfill(8) 在字符串的开头添加零,使其长度为 8,这是您的 output 格式所要求的。 Then it is typecasted into a list.然后将其类型转换为列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM