user3601754
user3601754

Reputation: 3862

Python - mask multidimensional

I would like to mask some values of an array. The array is 3D and the mask is 2D.

I want to mask all the coordonates in the direction of frametemperature_reshape.shape[0].

I tried the following loop:

for i in range(frametemperature_reshape.shape[0]):
    frames_BPnegl = np.ma.array(frametemperature_reshape[i,:,:], mask=mask2)

Upvotes: 0

Views: 2659

Answers (2)

ali_m
ali_m

Reputation: 74252

You can broadcast the 2D mask against the 3D array, so that its size is expanded along the 3rd dimension without actually duplicating it in memory:

import numpy as np

x = np.random.randn(10, 20, 30)
mask = np.random.randn(10, 20) > 0

# broadcast `mask` along the 3rd dimension to make it the same shape as `x`
_, mask_b = np.broadcast_arrays(x, mask[..., None])

xm  = np.ma.masked_array(x, mask_b)

Upvotes: 7

rroowwllaanndd
rroowwllaanndd

Reputation: 3958

One way to do this is to create a 3D mask based on replications of the 2D one across the third dimension as follows:

mask3 = mask2 * np.ones(3)[:, None, None].
masked_output = np.ma.array(frametemperature_reshape, mask=mask3)

Upvotes: 1

Related Questions