Array of indexes for each element alongs the first dimension in a 2D array (numpy., tensorflow)

后端 未结 2 1081
悲&欢浪女
悲&欢浪女 2020-12-22 03:10
indexes = np.array([[0,1,3],[1,2,4 ]])
data = np.random.rand(2,5)

Now, i would like an array of shape (2,3), where

result[0] = data[0         


        
2条回答
  •  执念已碎
    2020-12-22 04:02

    numpy has take_along_axis which does what you describe plus it also lets you choose the axis.

    Example:

    >>> a = np.arange(24).reshape(2,3,4)
    >>> i = np.random.randint(0,4,(2,3,5))
    >>> i
    array([[[3, 3, 0, 1, 3],
            [3, 1, 0, 3, 3],
            [3, 2, 0, 3, 3]],
    
           [[2, 3, 0, 0, 0],
            [1, 1, 3, 1, 2],
            [1, 3, 0, 0, 2]]])
    
    >>> np.take_along_axis(a, i, -1)
    array([[[ 3,  3,  0,  1,  3],
            [ 7,  5,  4,  7,  7],
            [11, 10,  8, 11, 11]],
    
           [[14, 15, 12, 12, 12],
            [17, 17, 19, 17, 18],
            [21, 23, 20, 20, 22]]])
    

提交回复
热议问题