Python 如何从 numpy 二维数组中提取子数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35681054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I extract a sub-array from a numpy 2d array?
提问by mengmengxyz
I'd like to extract a numpy array with a specified size from a numpy 2d array--essentially I want to crop the array. For example, if have a numpy array like this:
我想从一个 numpy 二维数组中提取一个具有指定大小的 numpy 数组——基本上我想裁剪这个数组。例如,如果有一个像这样的 numpy 数组:
([1,2,3],
[4,5,6],
[7,8,9])
I'd like to extract a 2x2 from it and the result should be:
我想从中提取一个 2x2,结果应该是:
([1,2],
[4,5])
How can I do that?
我怎样才能做到这一点?
回答by Mike Müller
Given this array:
鉴于此数组:
>>> a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
You can slice it along both dimensions:
您可以沿两个维度对其进行切片:
>>> a[:2,:2]
array([[1, 2],
[4, 5]])