2

Let's say I have a list of Numpy arrays with varying shapes and need to replace all values of 255 with 1.

A = np.array([[0,255], [0,0]])
B = np.array([[0, 255,255], [255,0,0]])
list_of_array = [A, B]  # list could have many more arrays

Methods like np.place() and X[X == 255] = 1 do not work on lists.

2 Answers 2

2

If you have to have a list of arrays, and want to modify the values in those arrays rather than creating new ones, then you can do it by iterating over the list.

import numpy as np

A = np.array([[0,255], [0,0]])
B = np.array([[0, 255,255], [255,0,0]])
list_of_array = [A, B]  # list could have many more arrays

for array in list_of_array:
    array[array == 255] = 1
Sign up to request clarification or add additional context in comments.

Comments

1

You can use np.where in a list comprehension to create a new list of modified arrays:

updated_arrays = [np.where(a == 255, 1, a) for a in list_of_array]

2 Comments

It may not matter for this use case, but using np.where will allocate new arrays that have 255 replaced with 1, rather than replacing the values in the existing arrays.
@JeremyMcGibbon Yes, you are correct. My intent was to create a new list of arrays and leave the original untouched. If one prefers to mutate the original list of arrays, then your method is best.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.