您可以用一些占位符值替换中间区域(我使用了-12345,在您的实际数据中不可能出现的任何内容都可以),然后选择不等于该值的所有内容:
>>> import numpy as np
>>> a = np.arange(1,26)
>>> a.shape = (5,5)
>>> a
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])
>>> a[1:4,1:4] = -12345
>>> a
array([[ 1, 2, 3, 4, 5],
[ 6, -12345, -12345, -12345, 10],
[ 11, -12345, -12345, -12345, 15],
[ 16, -12345, -12345, -12345, 20],
[ 21, 22, 23, 24, 25]])
>>> a[a != -12345]
array([ 1, 2, 3, 4, 5, 6, 10, 11, 15, 16, 20, 21, 22, 23, 24, 25])
如果您使用浮点数组而不是整数数组,则可以使用NaN和isfinite更优雅地执行此操作:
>>> a = np.arange(1,26).astype('float32')
>>> a.shape = (5,5)
>>> a[1:4,1:4] = np.nan
>>> a
array([[ 1., 2., 3., 4., 5.],
[ 6., nan, nan, nan, 10.],
[ 11., nan, nan, nan, 15.],
[ 16., nan, nan, nan, 20.],
[ 21., 22., 23., 24., 25.]], dtype=float32)
>>> a[np.isfinite(a)]
array([ 1., 2., 3., 4., 5., 6., 10., 11., 15., 16., 20.,
21., 22., 23., 24., 25.], dtype=float32)