How can I replace values ​​in a 4-dimensional array?

Let's say I have a 4D array that

(600, 1, 3, 3)

      

If you take the first 2 elements, they might look like this:

0 1 0
1 1 1
0 1 0

2 2 2
3 3 3
1 1 1

etc

      

I have a list containing specific weights that I want to replace with specific values ​​in an array. My intention is to use the index of the list item corresponding to the value in the array. Therefore this list

[0.1  1.1  1.2  1.3]

      

when applied to my array will give the following output:

0.1   1.1   0.1
1.1   1.1   1.1
0.1   1.1   0.1

1.2   1.2   1.2
1.3   1.3   1.3
1.1   1.1   1.1

etc

      

This method would have to work across all 600 array elements.

I can do this awkwardly using a loop for

and array[array==x] = y

or np.place

, but I wanted to avoid the loop and perhaps use a method that will replace all values ​​at once. Is there such an approach?

+3


source to share


1 answer


Quoting from @ Divakar's solution in the comments that solves the problem in a very efficient manner:



Just index into the: version of the array np.asarray(vals)[idx]

, where vals

list and idx

is an array. Or use np.take(vals, idx)

to convert an array under the hood.

+1


source







All Articles