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

2024-10-04 03:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想给一个具有行/列索引的数组建立索引。 我从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(一)个值


Tags: 函数npzeroscolumn矩阵数组arrayrow
2条回答

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

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

结果是这样的:

fanzy idx one per row

相关问题 更多 >