Remove columns where every value is masked

倾然丶 夕夏残阳落幕 提交于 2021-01-27 07:31:16

问题


I want to remove columns from a masked array where every value in the column is masked. So in the following example:

>>> import numpy as np
>>> test = np.array([[1,0,0],[0,3,0],[1,4,0]])
>>> test = np.ma.masked_equal(test,0)
>>> test
[[1 -- --]
[-- 3  --]
[1  4  --]],
>>> np.somefunction(test)
[[1  --]
 [-- 3 ]
 [1  4 ]]

what should np.somefunction() be to get the given output?


回答1:


You can use fancy indexing:

test[:, ~np.all(test.mask, axis=0)]
#masked_array(data =
# [[1 --]
# [-- 3]
# [1 4]],
#             mask =
# [[False  True]
# [ True False]
# [False False]],
#       fill_value = 0)



回答2:


test[:, ~np.all(test == 0, axis=0)]



回答3:


In [13]: test
Out[13]:
masked_array(data =
 [[1 -- --]
 [-- 3 --]
 [1 4 --]],
             mask =
 [[False  True  True]
 [ True False  True]
 [False False  True]],
       fill_value = 0)


In [14]: test[:, :2]
Out[14]:
masked_array(data =
 [[1 --]
 [-- 3]
 [1 4]],
             mask =
 [[False  True]
 [ True False]
 [False False]],
       fill_value = 0)


来源:https://stackoverflow.com/questions/19380996/remove-columns-where-every-value-is-masked

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