【问题标题】:Replacing the values of a numpy array of zeros using a array of indexes使用索引数组替换 numpy 零数组的值
【发布时间】:2021-05-25 21:49:19
【问题描述】:

我正在使用 numpy,但我遇到了索引问题,我有一个 numpy 零数组和一个二维索引数组,我需要使用这个索引来更改零数组的值1的值,我尝试了一些东西,但它不起作用,这是我尝试的。

import numpy as np

idx = np.array([0, 3, 4], 
               [1, 3, 5],
               [0, 4, 5]]) #Array of index

zeros = np.zeros(6) #Array of zeros [0, 0, 0, 0, 0, 0]

repeat = np.tile(zeros, (idx.shape[0], 1)) #This repeats the array of zeros to match the number of rows of the index array

res = []
for i, j in zip(repeat, idx):
        res.append(i[j] = 1) #Here I try to replace the matching index by the value of 1

output = np.array(res)

但我得到语法错误

expression cannot contain assignment, perhaps you meant "=="?

我想要的输出应该是

output = [[1, 0, 0, 1, 1, 0],
          [0, 1, 0, 1, 0, 1],
          [1, 0, 0, 0, 1, 1]]

这只是一个例子,idx 数组可以更大,我认为问题在于索引,我相信有一种非常简单的方法可以做到这一点,而无需重复零数组并使用 zip 函数,但我想不通,希望有帮助,谢谢!

编辑:当我将= 更改为== 时,我得到了一个不需要的布尔数组,所以我也不知道那里发生了什么。

【问题讨论】:

    标签: python numpy indexing


    【解决方案1】:

    您可以使用np.put_along_axis 根据idx 中的索引将值分配给数组repeat。这比循环更有效(也更容易)。

    import numpy as np
    
    idx = np.array([[0, 3, 4], 
                    [1, 3, 5],
                    [0, 4, 5]]) #Array of index
    
    zeros = np.zeros(6).astype(int) #Array of zeros [0, 0, 0, 0, 0, 0]
    repeat = np.tile(zeros, (idx.shape[0], 1))
    
    np.put_along_axis(repeat, idx, 1, 1)
    

    repeat 将是:

    array([[1, 0, 0, 1, 1, 0],
           [0, 1, 0, 1, 0, 1],
           [1, 0, 0, 0, 1, 1]])
    

    FWIW,您也可以直接通过传入形状来制作零数组:

    np.zeros([idx.shape[0], 6])
    

    【讨论】:

    • 嗨!,谢谢你的快速回答,我不知道 np.put,它正是我需要的,快速问题,在函数的参数中,1 代表值我需要更换,我猜另一个是数组的轴,对吧?感谢关于 np.zeros 形状的额外答案!
    • @CarlosEduardoCorpus 是的,这是正确的。你也可以用关键字来调用它,这样在这里会更清楚:np.put_along_axis(repeat, idx, values=1, axis=1)
    猜你喜欢
    • 2013-06-08
    • 2015-10-31
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2019-05-04
    • 2014-10-01
    • 1970-01-01
    相关资源
    最近更新 更多