【问题标题】:Array assignment without for loop [duplicate]没有for循环的数组赋值[重复]
【发布时间】:2018-02-14 14:00:54
【问题描述】:

我在为 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 循环。那么有人可以帮助我吗?

【问题讨论】:

    标签: python numpy indexing


    【解决方案1】:

    你可以这样做:

    >>> 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.]])
    

    【讨论】:

      猜你喜欢
      • 2016-01-17
      • 2012-10-24
      • 1970-01-01
      • 2015-07-04
      • 2015-03-01
      • 1970-01-01
      • 2017-10-20
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多