Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract a sub-array from a numpy 2d array? [duplicate]

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:

([1,2,3],  [4,5,6],  [7,8,9]) 

I'd like to extract a 2x2 from it and the result should be:

([1,2],  [4,5]) 

How can I do that?

like image 771
mengmengxyz Avatar asked Feb 28 '16 09:02

mengmengxyz


People also ask

How do I extract a sub array from an array in python?

To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.

How do you subset a NumPy 2D array?

Slice Two-dimensional Numpy Arrays To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .

How do I copy a NumPy array to another NumPy array?

Conclusion: to copy data from a numpy array to another use one of the built-in numpy functions numpy. array(src) or numpy. copyto(dst, src) wherever possible.


Video Answer


1 Answers

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]]) 
like image 123
Mike Müller Avatar answered Oct 02 '22 20:10

Mike Müller