使用bool数组掩码,用NaN替换False值

时间:2015-08-11 13:39:12

标签: python arrays numpy nan

我有两个数组,

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)

现在我希望使用b屏蔽a,在True中保留a值,并将False值替换为NaN ,获得一个形状类似a的新数组。

怎么做?

1 个答案:

答案 0 :(得分:8)

您可以使用boolean indexing

a[~b] = np.nan

这会将a中与False掩码b中的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]])

var result = this.context.Database.SqlQuery<SQLUserInfo>("SELECT SYSTEM_USER AS UserID");