Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple values of 3d Numpy array by list of indexes

I need to replace multiple values of a 3d NumPy array with other values using the list of indexes. For example:

old_array = np.full((224,224,3),10)
# in below list first position element are indexes and 2nd one are their corresponding values
list_idx_val = [[array([[ 2, 14,  0],
   [ 2, 14,  1],
   [ 2, 14,  2],
   [99, 59,  1],
   [99, 61,  1],
   [99, 61,  2]], dtype=uint8), array([175, 168, 166,119, 117, 119], dtype=uint8)]
#need to do
old_array[2,14,1] =168

One way is to simply access index values and replace old values with the new one. But the NumPy array and list of indexes is quite big. I would be highly thankful for a fast and efficient solution (without a loop, preferably slicing or other maybe) to replace the array values as I need to create thousands of arrays by replacing values using such list of indexes with minimal latency.

like image 785
Piyush Avatar asked Nov 22 '25 07:11

Piyush


1 Answers

Let's do array indexing:

idx, vals = list_idx_val

old_array[idx[:,0], idx[:,1], idx[:,2]] = vals

Output (plt.show):

enter image description here

like image 196
Quang Hoang Avatar answered Nov 24 '25 22:11

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!