简体   繁体   English

将矩阵中的值匹配到数组

[英]Matching values from a matrix to an array

I have a matrix of binary values with the size 211 x 129 eg:我有一个大小为 211 x 129 的二进制值矩阵,例如:

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:我有一个包含 211 个数字的数组:

   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.非常重要的是,数组中的数字(例如 158)恰好是矩阵的第 158 行。

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 .其中array - 1代表在 Python索引是基于 0的事实。


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]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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