简体   繁体   English

使用列索引向量将2D数组元素替换为零

[英]Replace 2D array elements with zeros, using a column index vector

I have a 2D array A: 我有一个二维数组A:

28  39  52
77  80  66   
 7  18  24    
 9  97  68

And a vector array of column indexes B: 还有列索引B的向量数组:

1   
0   
2    
0

How in a pythonian way, using base python or numpy, can I replace with zeros, elements on each row of A that correspond to the column indexes in B? 我如何以Python方式使用基本python或numpy,将A的每一行上与B中的列索引相对应的元素替换为零?

I should get the following new array A, with one element on each row (the one in the column index stored in B), replaced with zero: 我应该得到以下新数组A,每行一个元素(存储在B中的列索引中的一个元素),替换为零:

28   0  52
 0  80  66   
 7  18   0    
 0  97  68

Thanks for your help! 谢谢你的帮助!

Here's a simple, pythonian way using enumerate : 这是使用enumerate的一种简单的pythonian方法:

for i, j in enumerate(B):
    A[i][j] = 0
In [117]: A = np.array([[28,39,52],[77,80,66],[7,18,24],[9,97,68]])                                                     
In [118]: B = [1,0,2,0]                                                                                                 

To select one element from each row, we need to index the rows with an array that matches B : 要从每一行中选择一个元素,我们需要使用与B匹配的数组对行进行索引:

In [120]: A[np.arange(4),B]                                                                                             
Out[120]: array([39, 77, 24,  9])

And we can set the same elements with: 我们可以通过以下方式设置相同的元素:

In [121]: A[np.arange(4),B] = 0                                                                                         
In [122]: A                                                                                                             
Out[122]: 
array([[28,  0, 52],
       [ 0, 80, 66],
       [ 7, 18,  0],
       [ 0, 97, 68]])

This ends up indexing the points with indices (0,1), (1,0), (2,2), (3,0). 这样就结束了用索引(0,1),(1,0),(2,2),(3,0)索引点。

A list based 'transpose' generates the same pairs: 基于列表的“转置”生成相同的对:

In [123]: list(zip(range(4),B))                                                                                         
Out[123]: [(0, 1), (1, 0), (2, 2), (3, 0)]

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

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