Python Numpy:使用花式索引在2d中插入值,并使用2 x 1d

Python Numpy:使用花式索引在2d中插入值,并使用2 x 1d,python,arrays,numpy,matrix,indexing,Python,Arrays,Numpy,Matrix,Indexing,我想给一个具有行/列索引的数组建立索引。 我从argmax函数中提取了一个包含列号(列索引)的数组 有了这个,我想把一个零2D矩阵变成1(或True),因为索引对应于这个列索引。行从0到4 下面是我的试验和我如何看待这个问题 matrix1 = np.zeros((5, 10)) matrix2 = np.zeros((5, 10)) matrix3 = np.zeros((5, 10)) matrix4 = np.zeros((5, 10)) matrix5 = np.zeros((5, 10

我想给一个具有行/列索引的数组建立索引。 我从
argmax
函数中提取了一个包含列号(列索引)的数组

有了这个,我想把一个零2D矩阵变成1(或True),因为索引对应于这个列索引。行从0到4

下面是我的试验和我如何看待这个问题

matrix1 = np.zeros((5, 10))
matrix2 = np.zeros((5, 10))
matrix3 = np.zeros((5, 10))
matrix4 = np.zeros((5, 10))
matrix5 = np.zeros((5, 10))

row = np.array([0,1,2,3,4])
column = np.array([9,9,2,3,9,2,1,3,3,1])

matrix1[row, column] = 1
matrix2[[row, column]] = 1
matrix3[[row], [column]] = 1
matrix4[[[row], [column]]] = 1
matrix5[([row], [column])] = 1
我怎样才能使它按预期工作

编辑:
除上述情况外,还存在一种情况,即每行只需要1(一)个值。

这听起来有点天真,但凭直觉,我会首先找到所有可能的索引组合

matrix1 = np.zeros((5, 10))
row = np.array([0,1,2,3,4])
column = np.array([9,9,2,3,9,2,1,3,3,1])

index = np.stack(np.meshgrid(row,column), -1).reshape(-1,2) 
matrix1[index[:,0], index[:,1]] = 1

希望这能有所帮助。

除了上述情况外,还存在一种情况,即每行只需要1(一)个值。根据@hpaulj和@ashutosh chap的答案进行推断,如解决方案如下所示:

row = np.array([0,1,2,3,4])
column = np.array([9,9,2,3,9])

matrix2[row[:,None], column[:,None]] = 1
结果是这样的:


尝试使用
行[:,无]
作为行索引,换句话说,对行使用(5,1)。这将
broadcast
使用(10,)列来选择(5,10)个元素数组。谢谢,我将使用这个。谢谢,我标记了一个答案,因为它有效,但我看到了使用较短版本的好处,如@hpaulj建议的“row[:,None]”。谢谢你的帮助。