Waterploof
Waterploof

Reputation: 101

replace array elements with elements of a list in NumPy

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)

Upvotes: 2

Views: 143

Answers (1)

Jacques Kvam
Jacques Kvam

Reputation: 3076

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.

Upvotes: 1

Related Questions