在numpy 2D数组中获取包含非掩码值的第一行和最后一行的索引

时间:2018-09-27 08:24:16

标签: 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, 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;第六行(第5行)仅包含屏蔽值)
  • (1, 3)用于轴1(因为具有未屏蔽值的第一列为1,最后一列为3(第一和第五列仅包含屏蔽值))。

[我曾考虑过将numpy.ma.flatnotmasked_edgesnumpy.apply_along_axis组合在一起,但没有成功...]

2 个答案:

答案 0 :(得分:1)

您可以执行的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)

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)

答案 1 :(得分:1)

这里是一个bitbucket repository-

# 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