用索引数组更改numpy数组 [英] Changing numpy array with array of indices
本文介绍了用索引数组更改numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在numpy中有一个数组:
A=np.zeros((5,10))
我想根据另一数组N=np.array([7, 2, 9, 4, 5])
I have an array in numpy:
A=np.zeros((5,10))
and I want to change one value in each row with ones according to another array N=np.array([7, 2, 9, 4, 5])
like:A[:,N]=1;
0 0 0 0 0 1 0 0 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
我该怎么做?
推荐答案
由于您要设置每行单个元素,因此需要使用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]))
这篇关于用索引数组更改numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文