With a 2D masked array in Python, what would be the best way to get the index of the first and last rows and columns containing a non-masked value?
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 --]
# [-- -- -- -- --]]
In this example, I would like to obtain:
(0, 4)
for axis 0 (since the first row with unmasked value(s) is 0 and the last one is 4; the 6th row (row 5) only contains masked values)(1, 3)
for axis 1 (since the first column with unmasked value(s) is 1 and the last one is 3 (the 1st and 5th columns only contain masked values)).
[I thought about maybe combining numpy.ma.flatnotmasked_edges
and numpy.apply_along_axis
, without any success...]