3

Convert a tuple into a Numpy matrix with the below conditions:

  • The shape of the array should be len(tuple) x len(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?

2 Answers 2

3

Something like this? Manipulate the matrix is quite faster than for loop.

import numpy as np

t = (2, 0, 1)
x = np.zeros([len(t),len(t)])

for i,v in enumerate(t):
    x[i, v] = 1

print(x)

outputs:

[[0. 0. 1.]
 [1. 0. 0.]
 [0. 1. 0.]]
Sign up to request clarification or add additional context in comments.

1 Comment

more Intuitive, Thanks
3

For example (setting up from Ke)

t = (2, 0, 1)
x = np.zeros([len(t),len(t)])
x[np.arange(len(x)),t]=1
x
Out[145]: 
array([[0., 0., 1.],
       [1., 0., 0.],
       [0., 1., 0.]])

1 Comment

I like this one, more concise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.