[英]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: 我想要的意思是:
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.