Python 使用索引数组替换由零组成的numpy数组的值

Python 使用索引数组替换由零组成的numpy数组的值,python,numpy,indexing,Python,Numpy,Indexing,我在使用numpy,我在使用index时遇到了一个问题,我有一个numpy的零数组,还有一个2D的索引数组,我需要的是使用这个索引将零数组的值更改为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

我在使用numpy,我在使用index时遇到了一个问题,我有一个numpy的零数组,还有一个2D的索引数组,我需要的是使用这个索引将零数组的值更改为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函数,但我无法理解,任何帮助都会被推荐,谢谢

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

您可以使用
根据
idx
中的索引将值分配到数组中
重复。这比循环更有效(也更容易)

重复
将:

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.zero形状的补充回答@是的,没错。你也可以用关键字来称呼它,这会使它在这里更清晰:
np.沿着轴放置(重复,idx,value=1,axis=1)
np.zeros([idx.shape[0], 6])