简体   繁体   English

修改2D NumPy数组的每一行中的不同列

[英]Modify different columns in each row of a 2D NumPy array

I have the following problem: 我有以下问题:

Let's say I have an array defined like this: 假设我有一个像这样定义的数组:

A = np.array([[1,2,3],[4,5,6],[7,8,9]])

What I would like to do is to make use of Numpy multiple indexing and set several elements to 0. To do that I'm creating a vector: 我想要做的是利用Numpy多重索引并将几​​个元素设置为0.为此,我创建了一个向量:

indices_to_remove = [1, 2, 0]

What I want it to mean is the following: 我想要的意思是:

  1. Remove element with index '1' from the first row 从第一行删除索引为“1”的元素
  2. Remove element with index '2' from the second row 从第二行删除索引为“2”的元素
  3. Remove element with index '0' from the third row 从第三行删除索引为“0”的元素

The result should be the array [[1,0,3],[4,5,0],[0,8,9]] 结果应该是数组[[1,0,3],[4,5,0],[0,8,9]]

I've managed to get values of the elements I would like to modify by following code: 我设法通过以下代码获取我想要修改的元素的值:

values = np.diagonal(np.take(A, indices, axis=1))

However, that doesn't allow me to modify them. 但是,这不允许我修改它们。 How could this be solved? 怎么能解决这个问题?

You could use integer array indexing to assign those zeros - 您可以使用integer array indexing来分配这些零 -

A[np.arange(len(indices_to_remove)), indices_to_remove] = 0

Sample run - 样品运行 -

In [445]: A
Out[445]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

In [446]: indices_to_remove
Out[446]: [1, 2, 0]

In [447]: A[np.arange(len(indices_to_remove)), indices_to_remove] = 0

In [448]: A
Out[448]: 
array([[1, 0, 3],
       [4, 5, 0],
       [0, 8, 9]])

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

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