4

I need to assign one array to another using an index array. But some values are out of bounds...

a = np.array([0, 1, 2, 3, 4])
b = np.array([10, 11, 12, 13, 14])
indexes = np.array([0, 2, 3, 5, 6])

a and b are the same size. If I use a[indexes] = b, it would throw an IndexError. I want it to ignore the out of bounds values, 5 and 6, so that a would become [10, 1, 11, 12, 4].

I tried to do indexes[indexes > b.size()] = 0 but this would mess up the value at index 0. How can this be solved?

Edit

The indexes may not necessarily be in order. For example:

indexes = np.array([2, 3, 0, 5, 6])

a should become np.array([12, 1, 10, 11, 4])

2
  • In your edit, please where does the 11 (b at index 1) come from in expected result of a? Commented Jun 25, 2020 at 13:30
  • b should match with indexes, so b[1] should go to a[index[1]] Commented Jun 25, 2020 at 14:53

1 Answer 1

4

You can filter out those invalid indexes:

indexes = indexes[indexes < len(a)]

a[indexes] = b[indexes]

Output:

array([10,  1, 12, 13,  4])
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.