获取numpy2d数组中包含非任务值的第一行和最后一列的索引

2024-10-01 00:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

对于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结合起来,但没有任何成功…]


Tags: 方法importnumpyfalsetrueasnprange
2条回答

你可以做到:

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)

或者

^{pr2}$

这里有一个based on ^{}-

# 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

相关问题 更多 >