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])
You can filter out those invalid indexes:
indexes = indexes[indexes < len(a)]
a[indexes] = b[indexes]
Output:
array([10, 1, 12, 13, 4])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.