Convert a tuple into a Numpy matrix with the below conditions:
- The shape of the array should be
len(tuple)xlen(tuple), ie a square matrix. - Elements in array at the location specified by
(index of the element in the tuple, the value of the element in the tuple)should be one.
For example, I have a random tuple, like below:
# index means row ,value means col
(2,0,1)
I use two loop to change this tuple into Numpy array:
def get_np_represent(result):
two_D = []
for row in range(len(result)):
one_D = []
for col in range(len(result)):
if result[row] == col:
one_D.append(1)
else:
one_D.append(0)
two_D.append(one_D)
return np.array(two_D)
output:
array([[0, 0, 1],
[1, 0, 0],
[0, 1, 0]])
But I have 10,000,000 such tuple, Is there a faster way?