w3resource

NumPy: Convert a given vector of integers to a matrix of binary representation

NumPy: Array Object Exercise-187 with Solution

Write a NumPy program to convert a given vector of integers to a matrix of binary representation.

Pictorial Presentation:

Python NumPy: Convert a given vector of integers to a matrix of binary representation

Sample Solution:

Python Code:

import numpy as np
nums = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15])
print("Original vector:")
print(nums)
bin_nums = ((nums.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print("\nBinary representation of the said vector:")
print(bin_nums[:,::-1])

Sample Output:

Original vector:
[ 0  1  3  5  7  9 11 13 15]

Binary representation of the said vector:
[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 1 1]
 [0 0 0 0 0 1 0 1]
 [0 0 0 0 0 1 1 1]
 [0 0 0 0 1 0 0 1]
 [0 0 0 0 1 0 1 1]
 [0 0 0 0 1 1 0 1]
 [0 0 0 0 1 1 1 1]]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Write a NumPy program to multiply an array of dimension (2,2,3) by an array with dimensions (2,2).
Next: Write a NumPy program to extract rows with unequal values (e.g. [1,1,2]) from 10x3 matrix.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}