没有for循环的数组赋值

时间:2017-09-06 07:19:17

标签: python numpy indexing

在为numpy结构赋值时遇到问题。例如,假设我有一个numpy数组Src(N*K)和一个索引数组Index(N*1),其值在0~K-1之间。我的任务是根据索引将Src值分配给数组Target(N*1)

一种天真的方式是使用for循环:

for i in xrange(Index.shape[0]):
    Target[i,:] = Src[i,Index[i]]

但是,我认为应该有其他优雅的方式来实现这个任务而不用for循环。那么有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

>>> Target = np.zeros((4, 4))
>>> Src = np.ones((4, 4))
>>> Index = np.array([1, 2])
>>> Target[i, :] = Src[i, Index, None]
>>> Target
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
相关问题