How to properly mask a numpy 2D array?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to properly mask a numpy 2D array in Python. So Here I am Explain to you all the possible Methods here.

How to properly mask a numpy 2D array?

1. How to properly mask a numpy 2D array?

np.ma makes most sense when there's a scattering of masked values. It isn't of much value if you want want to select, or deselect, whole rows or columns.

2. properly mask a numpy 2D array

np.ma makes most sense when there's a scattering of masked values. It isn't of much value if you want want to select, or deselect, whole rows or columns.

Method 1

Is this what you are looking for?

import numpy as np
# array([[1, 2],
#        [2, 3]])

newX

#  [[1 2]
#  [2 3]
#  [-- --]],
#  [[False False]
#  [False False]
#  [ True  True]],
#        fill_value = 999999)

Method 2

Your x is 3×2:

In : x
Out:
array([[1, 2],
[2, 3],
[3, 4]])

Make a 3 element boolean mask:

That can be used to select the rows where it is True, or where it is False. In both cases the result is 2d:

Out: array([[3, 4]])

Out:
array([[1, 2],
[2, 3]])

This is without using the MaskedArray subclass. To make such array, we need a mask that matches x in shape. There isn’t provision for masking just one dimension.

Out:
array([[False, False],
[False, False],
[ True,  True]], dtype=bool)

Out:
[[1 2]
[2 3]
[-- --]],
[[False False]
[False False]
[ True  True]],
fill_value = 999999)

Applying compressed to that produces a raveled array: array([1, 2, 2, 3])

Since masking is element by element, it could mask one element in row 1, 2 in row 2 etc. So in general compressing, removing the masked elements, will not yield a 2d array. The flattened form is the only general choice.

np.ma makes most sense when there’s a scattering of masked values. It isn’t of much value if you want want to select, or deselect, whole rows or columns.

===============

Here are more typical masked arrays:

Out:
[[1 --]
[-- --]
[-- 4]],
[[False  True]
[ True  True]
[ True False]],
fill_value = 999999)

Out:
[[1 --]
[-- 3]
[3 4]],
[[False  True]
[ True False]
[False False]],
fill_value = 2)

Out:
[[-- 2]
[2 3]
[3 --]],