Numpy:使用花式索引在2d中插入带有2 x 1d的值

问题描述 投票:0回答:2

我想给定具有行/列索引的数组的索引。我有一个数组,其中包含从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(一个)值。

python arrays numpy matrix indexing
2个回答
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

希望这会有所帮助。


0
投票

除了上述情况外,还有一种情况是每行只需要1(一个)值。从@hpaulj和@ ashutosh-chapagain推断出答案,例如解决方案如下:

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

© www.soinside.com 2019 - 2024. All rights reserved.