0

I got a problem where I cant exchange values in an array. I've got 2 arrays, one filled with zeros and ones, for example: disp = [[0.], [0.], [0.], [1.], [1.], [1.], [1.], [0.], [0.], [0.]] and the other one filled with values I would like to implement at the place where the ones are in disp, for example: to_replace_at_1 = [[17.17], [0.], [-7.0] , [7.0]].

The result should look like this: disp = [[0.], [0.], [0.], [17.17], [0.], [-7.0], [7.0], [0.], [0.], [0.]].

I tried this:

        for i in range(len(disp)):
        vector = disp[i]
        for value in vector:
            if value == 1.0:
                for e in to_replace_at_1:
                    disp[i] = to_replace_at_1[e]

But it ends up crashing. What should I try? How do I solve this?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
WARIO
  • 23
  • 4
  • https://stackoverflow.com/questions/19984102/select-elements-of-numpy-array-via-boolean-mask-array may be helpful. – MattDMo Jan 03 '22 at 13:27
  • Are your "arrays" actually NumPy arrays, or are they pure Python lists of lists? – MattDMo Jan 03 '22 at 13:37

3 Answers3

1

One way to do it:

iterator = iter(to_replace_at_1)
[x if x[0] != 1 else next(iterator) for x in disp]
bb1
  • 7,174
  • 2
  • 8
  • 23
0

In your case it was crashing at disp[i] = to_replace_at_1[e] since e is a list in your case. Your logic implementation is good tho.

Not the best way I suppose but I can give you a working solution following code.

j = 0
for i in range(len(disp)):
    vector = disp[i]
    for value in vector:
        if value == 1.0:
            disp[i] = to_replace_at_1[j]
            j += 1
SneaKoa
  • 50
  • 4
0

This will do :

disp = [[0.], [0.], [0.], [1.], [1.], [1.], [1.], [0.], [0.], [0.]]
to_replace_at_1 = [[17.17], [0.], [-7.0] , [7.0]]

idx = 0

for i, val in enumerate(disp):
    if val[0] == 1.0:
        disp[i] = to_replace_at_1[idx]
        idx += 1


print(disp)
>>> [[0.0], [0.0], [0.0], [17.17], [0.0], [-7.0], [7.0], [0.0], [0.0], [0.0]]
NSegal
  • 56
  • 3