Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace values in a 4-dimensional array?

Let's say I have a 4D array that is

(600, 1, 3, 3)

If you take the first 2 elements they may 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 that contains certain weights that I want to replace specific values in the array. My intention is to use the index of the list element match the value in the array. Therefore, this list

[0.1  1.1  1.2  1.3]

when applied against my array would give this result:

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 run through the entire 600 elements of the array.

I can do this in a clunky way using a for loop and array[array==x] = y or np.place but I wanted to avoid a loop and perhaps use a method that at once will replace all values. Is there such an approach?

like image 454
pepe Avatar asked Apr 01 '26 00:04

pepe


1 Answers

Quoting from @Divakar's solution in the comments, which solves the issue in a very efficient manner:

Simply index into the array version: np.asarray(vals)[idx], where vals is the list and idx is the array. Or use np.take(vals, idx) to do the array conversion under the hood.

like image 70
pepe Avatar answered Apr 02 '26 12:04

pepe



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!