且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用索引数组更改numpy数组

更新时间:2022-11-24 19:21:16

由于您要设置每行单个元素,因此需要使用arange(5)花式索引第一个轴.可以将其视为设置索引(I0[0], N[0])=(0,7)(I0[1],N[1])=(1,2),...

Since you want to set a single element per row, you need to fancy-index the first axis using arange(5). this can be thought of as setting indices (I0[0], N[0])=(0,7), (I0[1],N[1])=(1,2), ...

I0 = np.arange(A.shape[0])
A[I0, N] = 1
A
=> 
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.]])
A.nonzero()
=> (array([0, 1, 2, 3, 4]), array([7, 2, 9, 4, 5]))