简体   繁体   English

使用同一数组中的另一个值作为索引替换numpy数组中的值

[英]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.

相关问题 用另一个数组的相同索引的值替换一个数组中的值? - Replacing a value from one array with a value of the same index of another array? python - 从具有相同行的向量中替换 numpy 数组的列给定索引 - python - Replacing value in a numpy array's column given index from a vector with the same rows 将一个数组的值替换为另一个数组的索引时,用另一个数组的值替换numpy数组中的值 - replacing the values in a numpy array with the values of another array against value of one array as index in another 用最大值替换numpy数组 - Replacing numpy array with max value 使用numpy,如何生成一个数组,其中每个索引的值是从0到第二个数组中相同索引的值的总和? - Using numpy, how can I generate an array where the value at each index is the sum of the values from 0 to that same index in a second array? Python:使用字典值作为numpy数组的索引 - Python: using dictionary value as an index into numpy array 从变量的索引获取numpy数组中的值 - Get a value in a numpy array from a index in a variable numpy:从(索引,值)字典创建数组 - numpy: create array from a (index,value) dict 如何使用另一个NumPy数组的值过滤NumPy数组 - How to filter a NumPy array using value of another NumPy Array Numpy:基于dict的值创建2D数组,使用其他2D数组值作为索引 - Numpy: Create 2D array based on value from dict, using other 2D array value as index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM