简体   繁体   中英

How to insert words in a numpy multidimensional array?

I need to put in a matrix some words that are taken from a list, based on their indices. My code is the following:

for i in range(no_of_lines):
    for j in range(no_of_lines):
        cuv_matrix[i][j] = cuv_list[mat_index[i][j]]

cuv_list is the list of words, and mat_index contains the indices that correspond to the ones in the cuv_list

The cuv_matrix actual output is this:

[['\x88' 'M' '\x93' ..., '6' '4' '1']
 ['2' '8' '3' ..., '0' '1' '6']
 ['0' '3' '2' ..., '.' '0' '0']
 ..., 
 ['\xff' '\xff' '\xff' ..., '' '0' '.']
 ['0' '' '0' ..., '' '0' '.']
 ['0' '' '0' ..., '0' '.' '0']]

The way I declared cuv_matrix:

cuv_matrix = numpy.chararray((no_of_lines, no_of_lines))

What am I doing wrong and how can I get each element of the matrix to be a word, like this?

Expected output:

[[movie film ..., actor]
      ... ...
character seen ..., director]]

Later on, I need to access the words from the matrix using their coordinates.

Thanks in advance!

If I understand you correctly, cuv_list is just a list, right?

so, you need an external counter.

k = 0
for i in range(no_of_lines):
    for j in range(no_of_lines):
        cuv_matrix[i][j] = cuv_list[k]
        k += 1

Looking at your question again, it seems like you might also want a dictionary to hold info:

cuv_mat = {}
k = 0
for i in range(no_of_lines):
    for j in range(no_of_lines):
        cuv_matrix[i][j] = cuv_list[k]
        cuv_mat[cuv_list[k]] = (i,j)
        k += 1

Or, in the case that you want to keep the coordinate info together with the original list and might have duplicates:

cuv_mat_locations = []
k = 0
for i in range(no_of_lines):
    for j in range(no_of_lines):
       cuv_matrix[i][j] = cuv_list[k]
       cuv_mat_locations.append([cuv_list[k], [i,j]])
       k += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM