[英]Replacing value in a numpy array using as an index another value from the same array
I am looking for an elegant way of doing the following: 我正在寻找一种优雅的方式来执行以下操作:
I have an array like this: 我有一个像这样的数组:
[[0, 0, 0, 1],
[0, 0, 0, 2],
[0, 0, 0, 1]]
I want to replace the element on each row, which index is equal to the last element of that row, with 1. So for the first row I need the element with index 1 to become 1, for the second row the element with an index 2 to become 1 and so on. 我想将每行的索引都等于1的元素替换为该行的最后一个元素,因此对于第一行,我需要将索引为1的元素变为1,对于第二行,需要将具有索引的元素替换为1 2变成1,依此类推。 This is just an example, in reality I have bigger matrices and the last column has values from 0 to 9, which I need to use to indicate which element of the row to become 1.
这只是一个例子,实际上我有更大的矩阵,最后一列的值从0到9,我需要用它来指示要变为1的那一行。
IIUC, you could use advanced indexing and do something like IIUC,您可以使用高级索引并执行类似的操作
>>> s
array([[0, 0, 0, 1],
[0, 0, 0, 2],
[0, 0, 0, 1]])
>>> s[np.arange(len(s)),s[:,-1]] = 1
>>> s
array([[0, 1, 0, 1],
[0, 0, 1, 2],
[0, 1, 0, 1]])
array = [[0, 0, 0, 1], [0, 0, 0, 2], [0, 0, 0, 1]]
for row in array:
row[row[-1]] = 1
Yields 产量
[[0, 1, 0, 1], [0, 0, 1, 2], [0, 1, 0, 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.