[英]mask a 2D numpy array based on values in one column
假設我有以下numpy數組:
a = [[1, 5, 6],
[2, 4, 1],
[3, 1, 5]]
我想掩蓋第一列中有1
所有行。 那就是我想要的
[[--, --, --],
[2, 4, 1],
[3, 1, 5]]
這是否可以使用numpy蒙面數組操作? 怎么能這樣做?
謝謝。
import numpy as np
a = np.array([[1, 5, 6],
[2, 4, 1],
[3, 1, 5]])
np.ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==1)).T)
# Returns:
masked_array(data =
[[-- -- --]
[2 4 1]
[3 1 5]],
mask =
[[ True True True]
[False False False]
[False False False]])
您可以通過創建所需的蒙版
mask = numpy.repeat(a[:,0]==1, a.shape[1])
和掩蓋的數組
masked_a = numpy.ma.array(a, mask=numpy.repeat(a[:,0]==1, a.shape[1]))
您可以簡單地創建一個空掩碼,然后使用numpy-broadcasting(如@eumiro顯示)但使用元素和按位“或”運算符|
:
>>> a = np.array([[1, 5, 6], [2, 4, 1], [3, 1, 5]])
>>> mask = np.zeros(a.shape, bool) | (a[:, 0] == 1)[:, None]
>>> np.ma.array(a, mask=mask)
masked_array(data =
[[-- -- --]
[2 4 1]
[3 1 5]],
mask =
[[ True True True]
[False False False]
[False False False]],
fill_value = 999999)
進一步解釋:
>>> # select first column
>>> a[:, 0]
array([1, 2, 3])
>>> # where the first column is 1
>>> a[:, 0] == 1
array([ True, False, False], dtype=bool)
>>> # added dimension so that it correctly broadcasts to the empty mask
>>> (a[:, 0] == 1)[:, None]
array([[ True],
[False],
[False]], dtype=bool)
>>> # create the final mask
>>> np.zeros(a.shape, bool) | (a[:, 0] == 1)[:, None]
array([[ True, True, True],
[False, False, False],
[False, False, False]], dtype=bool)
這種方法的另一個優點是它不需要使用可能昂貴的乘法或np.repeat
所以它應該非常快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.