Piyush
Piyush

Reputation: 388

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.

Upvotes: 3

Views: 807

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

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

Upvotes: 1

Related Questions