获取 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, 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, 4) 对于轴 0(因为未屏蔽值的第一行是 0,最后一行是 4;第 6 行(第 5 行)仅包含屏蔽值)

  • (1, 3) 对于轴 1(因为具有未屏蔽值的第一列是 1,而最后一列是 3(第 1 列和第 5 列仅包含屏蔽值))。

[我想过可能结合numpy.ma.flatnotmasked_edgesnumpy.apply_along_axis,但没有成功......]


PIPIONE
浏览 279回答 2
2回答

素胚勾勒不出你

IIUC你可以这样做:d = amask==False #First know which array values are maskedrows,columns = np.where(d) #Get the positions of row and column of masked valuesrows.sort() #sort the row valuescolumns.sort() #sort the column valuesprint('Row values :',(rows[0],rows[-1])) #print the first and last rowsprint('Column values :',(columns[0],columns[-1])) #print the first and last columnsRow values : (0, 4)Column values : (1, 3)或者rows, columns = np.nonzero(~a.mask)print('Row values :',(rows.min(), rows.max())) #print the min and max rowsprint('Column values :',(columns.min(), columns.max())) #print the min and max columnsRow values : (0, 4)Column values : (1, 3)

哈士奇WWW

这是一个基于argmax-# Get mask for any data along axis=0,1 separatelym0 = a.all(axis=0)m1 = a.all(axis=1)# Use argmax to get first and last non-zero indices along axis=0,1 separatelyaxis0_out = m1.argmax(), a.shape[0] - m1[::-1].argmax() - 1axis1_out = m0.argmax(), a.shape[1] - m0[::-1].argmax() - 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python