【发布时间】: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 函数,但我想不通,希望有帮助,谢谢!
编辑:当我将= 更改为== 时,我得到了一个不需要的布尔数组,所以我也不知道那里发生了什么。
【问题讨论】: