2

I have a NumPy array and I converted it into a matrix called string_matrix where each element is a string. Now I want to convert each element in string_matrix to letters. The number in matrix are the index of the list alp. So I want this output : string_matrix = [['l' 'i' 'a']['a' 'f' 'b']['u' 'e' 'k']]

alp = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",""]
matrix = numpy.array([[11, 8, 0],[0, 5, 1],[20, 4, 10]])
string_matrix = numpy.array(["%.f" % v for v in matrix.reshape(matrix.size)])
string_matrix = string_matrix.reshape(matrix.shape)

1 Answer 1

1

You can index into the alp list with your matrix, you need to make alp a numpy array first:

numpy.array(alp)[matrix]

Output:

array([['l', 'i', 'a'],
       ['a', 'f', 'b'],
       ['u', 'e', 'k']], dtype='<U1')

This uses numpy's advanced indexing. You can find more details here if you want to read up on it.

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to use a loop instead of this numpy's advanced indexing ?
Yea you can loop over the elements of the matrix and index into alp with its individual elements, rows, or columns. What do you want to loop over?
Over its individual elements but I solved this problem, thank you

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.