我有一个2D Numpy数组,其中包含一个被NaN海洋包围的数据孤岛。
我想裁剪数组,使其只包含边界框和非NaN区域的内容。
我还想知道这个框相对于原始数组的索引和大小。
这个是可能的吗?
发布于 2014-09-14 15:52:59
import numpy as np
a = np.empty((15,10))
a.fill(np.nan)
a[7,6] = 76
a[8,5] = 85
a[9,5] = 95
a[9,7] = 97
现在我们有一个15行10列的数组,在NAN的海洋中包含一个数据孤岛:
nan, 76., nan,
85., nan, nan,
95., nan, 97.,
接下来:
nans = np.isnan(a)
nancols = np.all(nans, axis=0) # 10 booleans, True where col is all NAN
nanrows = np.all(nans, axis=1) # 15 booleans
firstcol = nancols.argmin() # 5, the first index where not NAN
firstrow = nanrows.argmin() # 7
lastcol = len(nancols) - nancols[::-1].argmin() # 8, last index where not NAN
lastrow = len(nanrows) - nanrows[::-1].argmin() # 10
最后:
a[firstrow:lastrow,firstcol:lastcol]
向我们展示小岛:
array([[ nan, 76., nan],
[ 85., nan, nan],
[ 95., nan, 97.]])
https://stackoverflow.com/questions/25831023
复制相似问题