Replace values in array of indexes corresponding to another array

后端 未结 6 1680
Happy的楠姐
Happy的楠姐 2020-12-20 03:22

I have an array A of size [1, x] of values and an array B of size [1, y] (y > x) of indexes corresponding to array

6条回答
  •  無奈伤痛
    2020-12-20 04:09

    For fetching multiple items operator.itemgetter comes in handy:

    from operator import itemgetter
    A = [6, 7, 8]
    B = [0, 2, 0, 0, 1]
    
    itemgetter(*B)(A)
    # (6, 8, 6, 6, 7)
    

    Also as you've mentioned numpy, this could be done directly by indexing the array as you've specified, i.e. A[B]:

    import numpy as np
    A = np.array([6, 7, 8])
    B = np.array([0, 2, 0, 0, 1])
    
    A[B]
    # array([6, 8, 6, 6, 7])
    

    Another option is to use np.take:

    np.take(A,B)
    # array([6, 8, 6, 6, 7])
    

提交回复
热议问题