'How to replace a list inside a multildimensional array?

I was solving this question on SO and faced a few problems with the methods I was trying.

OP has a list which looks like this,

a = [[[100, 90, 80, 255], 
      [80, 10, 10, 255]], 
     [[0, 0, 0, 255],
      [0, 0, 0, 255]]]

And they want to replace [0,0,0,255] with [0,0,0,0].


For this, I first tried using np.where(a == [0,0,0,255]) to get all the indices of this list's occurrences but the output was an empty array.

Next, I tried converting the array into a pandas dataframe and applied the replace function and on it and still the dataframe remained the same.

What are the reasons for np.where giving me an empty array and replace not changing the dataframe, and how can I fix this?



Solution 1:[1]

You have to convert a to numpy array and use:

a = np.array(a)
a[(a == [0, 0, 0, 255]).all(axis=2)] = [0, 0, 0, 0]

Output:

>>> a
array([[[100,  90,  80, 255],
        [ 80,  10,  10, 255]],

       [[  0,   0,   0,   0],
        [  0,   0,   0,   0]]])

>>> a.tolist()
[[[100, 90, 80, 255], [80, 10, 10, 255]], [[0, 0, 0, 0], [0, 0, 0, 0]]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien