Python 获取numpy 2D数组中包含非屏蔽值的第一行和最后一行和列的索引

Python 获取numpy 2D数组中包含非屏蔽值的第一行和最后一行和列的索引,python,arrays,numpy,Python,Arrays,Numpy,对于Python中的2D屏蔽数组,获取包含非屏蔽值的第一行和最后一行和列的索引的最佳方法是什么 import numpy as np a = np.reshape(range(30), (6,5)) amask = np.array([[True, True, False, True, True], [True, False, False, True, True], [True, True, True, False, Tru

对于Python中的2D屏蔽数组,获取包含非屏蔽值的第一行和最后一行和列的索引的最佳方法是什么

import numpy as np
a = np.reshape(range(30), (6,5))
amask = np.array([[True, True, False, True, True],
                  [True, False, False, True, True],
                  [True, True, True, False, True],
                  [True, False, False, False, True],
                  [True, True, True, False, True],
                  [True, True, True, True, True]])
a = np.ma.masked_array(a, amask)
print a
# [[-- -- 2 -- --]
#  [-- 6 7 -- --]
#  [-- -- -- 13 --]
#  [-- 16 17 18 --]
#  [-- -- -- 23 --]
#  [-- -- -- -- --]]
在本例中,我希望获得:

  • 轴0的
    (0,4)
    (因为具有未屏蔽值的第一行为0,最后一行为4;第六行(第5行)仅包含屏蔽值)
  • 轴1的
    (1,3)
    (因为具有未屏蔽值的第一列为1,最后一列为3(第一列和第五列仅包含屏蔽值))
[我想也许可以将
numpy.ma.flatnotmasked_边
numpy.apply_沿_轴
,但没有任何成功…]

IIUC您可以做:

d = amask==False #First know which array values are masked
rows,columns = np.where(d) #Get the positions of row and column of masked values

rows.sort() #sort the row values
columns.sort() #sort the column values

print('Row values :',(rows[0],rows[-1])) #print the first and last rows
print('Column values :',(columns[0],columns[-1])) #print the first and last columns

Row values : (0, 4)
Column values : (1, 3)

这里有一个-


你能解释一下预期的结果吗?@Divakar我编辑了我的问题-希望现在更清楚。谢谢!IIUC,对我来说,做
行,列=np.nonzero(~a.mask)
然后
(rows.min(),rows.max())
(columns.min(),columns.max())
?我喜欢这种方法@你也可以这样做。
rows, columns = np.nonzero(~a.mask)
print('Row values :',(rows.min(), rows.max())) #print the min and max rows
print('Column values :',(columns.min(), columns.max())) #print the min and max columns

Row values : (0, 4)
Column values : (1, 3)
# Get mask for any data along axis=0,1 separately
m0 = a.all(axis=0)
m1 = a.all(axis=1)

# Use argmax to get first and last non-zero indices along axis=0,1 separately
axis0_out = m1.argmax(), a.shape[0] - m1[::-1].argmax() - 1
axis1_out = m0.argmax(), a.shape[1] - m0[::-1].argmax() - 1