Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filling in a numpy ndarray with a 1d array and a mask/index of true/false values

Let’s say I have the following:

import numpy as np
X = np.array([[1, 2, 3], [4, 5, 6]])
mask = np.array([[False, False, True], [False, True, False]])
values = np.array([20, 30])

I want to fill in the values of 20 and 30 in where the mask is true row wise so the result is:
[[1, 2, 20], [4, 30, 6]].

Also, how would I fill in the vector column wise so the result would be:
[[1, 2, 30], [4, 20, 6]].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How would I do this with just numpy?

>Solution :

X[mask] = values. This works when X.shape == mask.shape and len(values) == mask.sum().

Output:

array([[ 1,  2, 20],
       [ 4, 30,  6]])

For the second part of your question, you can transpose X and mask for the computation:

X.T[mask.T] = values

Output:

array([[ 1,  2, 30],
       [ 4, 20,  6]])

See the numpy documentation

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading