Char
Char

Reputation: 1735

Replacing values in a list of Numpy arrays

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.

Upvotes: 2

Views: 2048

Answers (2)

Jeremy McGibbon
Jeremy McGibbon

Reputation: 3775

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

Upvotes: 2

Alexander
Alexander

Reputation: 109546

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]

Upvotes: 1

Related Questions