0

I have two np array A and B and one index list, where:

A = np.arange(12).reshape(3,2,2)
>>> A
array([[[ 0,  1],
        [ 2,  3]],

       [[ 4,  5],
        [ 6,  7]],

       [[ 8,  9],
        [10, 11]]])

>>> B:
array([[[10, 10],
        [10, 10]],

       [[20, 20],
        [20, 20]]])

index_list = [0,2]

I would like to replace array A by entire array B based on index the index_list gives, which is 0 and 2 (corresponding to A's index at axis=0):

# desired output:
array([[[ 10,  10],
        [ 10,  10]],

       [[ 4,  5],
        [ 6,  7]],

       [[ 20,  20],
        [20, 20]]])

I have been thinking about implementing this process in a more efficient way, but only come up with two loops:

row_count = 0
for i,e in enumerate(A):
    for idx in index_list:
        if i == idx:
            A[i,:,:] = B[row_count,:,:]
            row_count += 1

which is computational expensive because I have two huge np arrays to process... it would be very appreciated if anyone have any idea of how to implement this process in vectorization way or in a more efficient way. Thanks!

4
  • Does A[index_list] give the elements you want to replace? Commented Aug 6, 2021 at 2:06
  • yes, that's correct, A[index_list] will be replace by entire B. Commented Aug 6, 2021 at 2:20
  • 1
    So does A[index_list]=B do what you want? Commented Aug 6, 2021 at 2:25
  • Yes, this helps too, thanks! Commented Aug 18, 2021 at 22:02

1 Answer 1

2

Have you tried just assigning like this:

A[index_list[0]] = B[0]
A[index_list[1]] = B[1]

I guess if you had a bigger number of indexes in the index_list, and more to replace, you could then make a loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.