[英]Python: extract the core of a 2D numpy array
Say I have a 2D numpy array like this: 说我有一个二维的numpy数组,像这样:
In[1]: x
Out[1]:
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5]], dtype=int64)
and I want to extract the (n-1)*(m-1)
core, which would be: 我想提取(n-1)*(m-1)
核心,它是:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]], dtype=int64)
How could I do this, since the data structure is not flat ? 由于数据结构不平坦 ,我该怎么办? Do you suggest flattening it first? 您建议先展平吗?
This is a simplified version of a much bigger array, which core has dimension (n-33)*(n-33)
. 这是更大数组的简化版本,该数组的维度为(n-33)*(n-33)
。
You can use negative stop indices to exclude the last x rows/columns and normal start indices: 您可以使用负停止索引来排除最后的x行/列和常规开始索引:
>>> x[1:-1, 1:-1]
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]], dtype=int64)
For your new example: 对于您的新示例:
>>> t = np.array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5]], dtype=np.int64)
>>> t[1:-1, 1:-1]
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]], dtype=int64)
You could also remove 2 leading and trailing columns: 您还可以删除2个前导列和尾随列:
>>> t[1:-1, 2:-2]
array([[1],
[2],
[3],
[4]], dtype=int64)
or rows: 或行:
>>> t[2:-2, 1:-1]
array([[2, 2, 2],
[3, 3, 3]], dtype=int64)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.