0

Problem

I have valid_data (1D np.array with nonzero values) and mask (boolean 1D np.array), which are not of the same size. The mask contains the wanted positions of the valid_data in a new np.array to create. Can I initialize this new np.array easily, or do I have to calculate it value by value?

Example

>>> mask = np.array([False, True, False, False, False, True, True, False, False, False])
>>> valid_data = np.array([1, 3, 3])
>>> 
>>> wanted_result = np.array([0, 1, 0, 0, 0, 3, 3, 0, 0, 0])
>>> 
>>> my_try = np.where(mask, valid_data, 0)

But I can't use np.where with arrays of different shapes. We can assume that the number of True values in mask matches the number of values in valid_data.

1 Answer 1

1

Create an array of zeros using np.zeros with the length of mask, and then assign the values from valid_data where mask is True:

arr = np.zeros(len(mask), dtype=int)
arr[mask] = valid_data

Output:

array([0, 1, 0, 0, 0, 3, 3, 0, 0, 0])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.