Replace values in array of indexes corresponding to another array

后端 未结 6 1710
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:21

    This is one way, using numpy ndarrays:

    import numpy as np
    
    A = [6, 7, 8]
    B = [0, 2, 0, 0, 1]
    C = list(np.array(A)[B]) # No need to convert B into an ndarray
                             # list() is for converting ndarray back into a list,
                             # (if that's what you finally want)
    print (C)
    

    Explanation

    1. Given a numpy ndarray (np.array(A)), we can index into it using an array of integers (which happens to be exactly what your preferred form of solution is): The array of integers that you use for indexing into the ndarray, need not be another ndarray. It can even be a list, and that suits us too, since B happens to a list. So, what we have is:

      np.array(A)[B]
      
    2. The result of such an indexing would be another ndarray, having the same shape (dimensions) as the array of indexes. So, in our case, as we are indexing into an ndarray using a list of integer indexes, the result of that indexing would be a one-dimensional ndarray of the same length as the list of indexes.

    3. Finally, if we want to convert the above result, from a one-dimensional ndarray back into a list, we can pass it as an argument to list():

      list(np.array(A)[B])
      

提交回复
热议问题