I have a binary list of string numbers as following:
['0b111',
'0b1110011',
'0b1110100',
'0b11101001',
'0b1100111',
'0b1100001',
'0b1101110',
'0b1101111']
And I would like to put this list into a 2D array of integers as following:
array([[0, 0, 0, 0, 0, 1, 1, 1],
[0, 1, 1, 1, 0, 0, 1, 1],
[0, 1, 1, 1, 0, 1, 0, 0],
[1, 1, 1, 0, 1, 0, 0, 1],
[0, 1, 1, 0, 0, 1, 1, 1],
[0, 1, 1, 0, 0, 0, 0, 1],
[0, 1, 1, 0, 1, 1, 1, 0],
[0, 1, 1, 0, 1, 1, 1, 1]], dtype=uint8)
I have first removed the '0b' of the binary sequences and put it in the res list. Then I've created a 2D array in order to put my list into it. And I have tried to do a double loop but I'm a bit confusing with it :
res = []
for i in range(len(conv_bin)):
res.append(conv_bin[i][2:])
arr = np.array(res)
arr2 = np.zeros((8,8))
for i in range(arr.shape[0]):
for j in range(arr2.shape[0]):
arr2[i] = arr[j]
3 Answers 3
You can use the numpy unpackbits function to help.
import numpy as np
conv_bin = ['0b111',
'0b1110011',
'0b1110100',
'0b11101001',
'0b1100111',
'0b1100001',
'0b1101110',
'0b1101111']
np.unpackbits(np.array([[int(s,2)] for s in conv_bin], dtype=np.uint8), axis=1)
Comments
If you want to use for loops you can use this:
import numpy as np
conv_bin=['0b111',
'0b1110011',
'0b1110100',
'0b11101001',
'0b1100111',
'0b1100001',
'0b1101110',
'0b1101111']
res =[]
for string in conv_bin:
ls=[]
string=string[2:]
for ch in string:
ls.append(ch)
res.append(ls)
Comments
- I think you can avoid the creation of multiple new lists like res and arr2 as well with the solution I'm writing below.
- A simple solution would be to traverse the binary matrix in reverse order
arr2 = np.zeros((8,8))
for i in range(len(conv_bin)):
'''
1. zip is function is to loop across two variables in this for loop
2. j is traversing each binary in the reverse order only until the 2nd index,
3. k is used to index the resultant array from reverse (we need different variables since the index values differ)
'''
for j,k in zip(range(len(conv_bin[i])-1, 1, -1), range(-1,-9,-1 )):
arr2[i][k] = conv_bin[i][j]
PS - In case you didn't know, in python you can index array from the reverse like this:
arr[-1] -> last element of array
arr[-2] -> last but one element
arr[-3] -> last but two elements and so on
Hope I've been clear in my answer