简体   繁体   中英

Matching values from a matrix to an array

I have a matrix of binary values with the size 211 x 129 eg:

matrix =

(

   0   0   1   1   0   0   0   0   0 ...   0   1   1   0   0   0   0   
   0   0   1   1   0   1   1   0   0 ...   0   0   0   0   0   0   0   
   0   0   0   0   0   0   0   0   0 ...   0   0   0   0   0   0   0   
   0   0   0   0   0   0   0   0   1 ...   0   0   0   0   0   0   0 
   ...
   ...
   ...  

)

and I have an array of 211 numbers:

   array =

 [

   [158 147  35 162 143 139   8 129  43  97 163 151  24 103 161  54  38  10
    100 193 192 191 188 187 186 185 184 182 181 179 178 177 176 175 174 171
    170 169 167 166 155 154 152 149 148 146 145 142 141 136 134 132 130 
   ....

 ]

I would like to match the numbers to the corresponding row in the array and create a new matrix. Very important is that the number from the array eg 158 gets exactly row 158 of the matrix.

The output would look like this:

   new_matrix:

 (

   158 0   0   0   1   0   0   0   0   0 ...   0   0   1   0   0   0   0 //Values of row 158 from the matrix     
   147 0   0   1   0   0   1   1   0   0 ...   0   0   0   0   0   0   0 //Values of row 147 from the matrix     
   35  0   0   1   1   0   0   0   0   0 ...   0   0   0   0   0   0   0    //Values of row 35 from the matrix   
   162 0   0   0   0   0   0   0   0   1 ...   0   0   0   0   0   1   1 

   143 
   ...
   ...

 )

Any guidance?

Make a matrix:

matrix = [[] for _ in range(211)]

Now, you can populate it:

for row in enumerate(array):
    matrix[row[0]] = old_matrix[row[1]]

What about doing

matrix[array - 1, :]

Where array - 1 stands for the fact that indexing is 0-based in Python .


An example, imitating your inputs.

>>> matrix[array - 1, :]
array([[0.15894248, 0.21096647, 0.5282654 , 0.69521   ],
       [0.15894248, 0.21096647, 0.5282654 , 0.69521   ],
       [0.56091075, 0.92830105, 0.63612971, 0.54486469]])

Finally

>>> matrix[array - 1, :] array([[0.15894248, 0.21096647, 0.5282654 , 0.69521 ], [0.15894248, 0.21096647, 0.5282654 , 0.69521 ], [0.56091075, 0.92830105, 0.63612971, 0.54486469]])

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