I have two arrays,
a = array([
[ 0.93825418, 0.60731973, 0.44218921, 0.90888805, 0.97695114],
[ 0.27422807, 0.75870153, 0.12154102, 0.89137678, 0.04257262],
[ 0.32855867, 0.17215507, 0.00302302, 0.95395069, 0.02596567],
[ 0.18385244, 0.09108341, 0.27925367, 0.0177183 , 0.41035188],
[ 0.87229432, 0.73573982, 0.98554476, 0.72321398, 0.98316711],
[ 0.16474265, 0.5308054 , 0.27913615, 0.59107689, 0.6480463 ],
[ 0.88356436, 0.22343885, 0.74900285, 0.43895017, 0.74993129],
[ 0.08097611, 0.48984607, 0.33991052, 0.06431022, 0.10753135],
[ 0.67351561, 0.13165046, 0.41327765, 0.21768539, 0.7337069 ],
[ 0.65609999, 0.06241059, 0.3400624 , 0.13234171, 0.23679716]
])
b = array([
[False, True, True, False, False],
[ True, False, False, False, False],
[ True, True, False, False, False],
[False, False, True, False, True],
[False, False, False, True, False],
[False, True, True, True, True],
[False, True, False, True, True],
[False, True, True, False, False],
[ True, True, True, True, True],
[ True, False, True, False, True]
], dtype = bool)
Now I want using b
to mask a
, retain the True
value in a
, and replace the False
value with NaN
, getting a new array that has a shape like a
.
How to do that?
You can use numpy. nan_to_num : numpy. nan_to_num(x) : Replace nan with zero and inf with finite numbers.
This can be done by using the fillna() method. The basic operation of this pandas series. fillna() method is used to replace missing values (Nan or NA) with a specified value. Initially, the method verifies all the Nan values and replaces them with the assigned replacement value.
nan is always false in the output.
You can use boolean indexing:
a[~b] = np.nan
This replaces all of values in a
that correspond to False
values in the mask b
with np.nan
:
>>> a
array([[ nan, 0.60731973, 0.44218921, nan, nan],
[ 0.27422807, nan, nan, nan, nan],
[ 0.32855867, 0.17215507, nan, nan, nan],
[ nan, nan, 0.27925367, nan, 0.41035188],
[ nan, nan, nan, 0.72321398, nan],
[ nan, 0.5308054 , 0.27913615, 0.59107689, 0.6480463 ],
[ nan, 0.22343885, nan, 0.43895017, 0.74993129],
[ nan, 0.48984607, 0.33991052, nan, nan],
[ 0.67351561, 0.13165046, 0.41327765, 0.21768539, 0.7337069 ],
[ 0.65609999, nan, 0.3400624 , nan, 0.23679716]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With