Mask specific columns of a numpy array

只愿长相守 提交于 2019-12-21 14:58:43

问题


I have a 2D numpy array A of (60,1000) dimensions.
Say, I have a variable idx=array([3,72,403, 512, 698]).

Now, I want to mask all the elements in the columns specified in idx. The values in these columns might appear in other columns but they shouldn't be masked.

Any help would be appriciated.


回答1:


In [22]: A = np.random.rand(5, 10)

In [23]: idx = np.array([1, 3, 5])

In [24]: m = np.zeros_like(A)

In [25]: m[:,idx] = 1

In [26]: Am = np.ma.masked_array(A, m)

In [27]: Am
Out[27]: 
masked_array(data =
 [[0.680447483547 -- 0.290757600047 -- 0.0718559525615 -- 0.334352145502
  0.0861242618662 0.527068091963 0.136280743038]
 [0.729374999214 -- 0.76026650048 -- 0.656082247985 -- 0.492464543871
  0.903026937193 0.0792660503403 0.892132409419]
 [0.0845266821684 -- 0.838838594048 -- 0.396344231382 -- 0.703748703373
  0.380441396691 0.010521007806 0.344945867845]
 [0.7501401585 -- 0.0685427000113 -- 0.587100320511 -- 0.780160645327
  0.276328587928 0.0665949459004 0.604174142611]
 [0.599926798275 -- 0.686378805503 -- 0.776940069716 -- 0.0452833614622
  0.598622591094 0.942843765543 0.528082379918]],
             mask =
 [[False  True False  True False  True False False False False]
 [False  True False  True False  True False False False False]
 [False  True False  True False  True False False False False]
 [False  True False  True False  True False False False False]
 [False  True False  True False  True False False False False]],
       fill_value = 1e+20)


来源:https://stackoverflow.com/questions/14611250/mask-specific-columns-of-a-numpy-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!