为了账号安全,请及时绑定邮箱和手机立即绑定

获取 numpy 二维数组中包含非屏蔽值的第一行和最后一行的索引

获取 numpy 二维数组中包含非屏蔽值的第一行和最后一行的索引

PIPIONE 2021-06-18 06:04:14
使用 Python 中的 2D 屏蔽数组,获取包含非屏蔽值的第一行和最后一行和列的索引的最佳方法是什么?import numpy as npa = 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_edges和numpy.apply_along_axis,但没有成功......]
查看完整描述

2 回答

?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

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)


查看完整回答
反对 回复 2021-06-29
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

这是一个基于argmax-


# 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


查看完整回答
反对 回复 2021-06-29
  • 2 回答
  • 0 关注
  • 278 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号