Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: slicing a multi-dimensional array

I'm new to Python and numpy. I've figured out how to slice 1 dimensional sequence: arr[start:end], and access an element in the array: el = arr[row][col].

Trying something like slice = arr[0:2][0:2] (where arr is a numpy array) doesn't give me the first 2 rows and columns, but repeats the first 2 rows. What did I just do, and how do I slice along another dimension?

like image 884
SlightlyCuban Avatar asked Jun 24 '13 13:06

SlightlyCuban


People also ask

How do you slice a multi dimensional array in Python?

I've figured out how to slice 1 dimensional sequence: arr[start:end] , and access an element in the array: el = arr[row][col] . Trying something like slice = arr[0:2][0:2] (where arr is a numpy array) doesn't give me the first 2 rows and columns, but repeats the first 2 rows.

Can you slice an array in Python?

Python has an amazing feature just for that called slicing. Slicing can not only be used for lists, tuples or arrays, but custom data structures as well, with the slice object, which will be used later on in this article.

Can you slice numpy arrays?

You can slice a numpy array is a similar way to slicing a list - except you can do it in more than one dimension.


1 Answers

If you use numpy, this is easy:

slice = arr[:2,:2] 

or if you want the 0's,

slice = arr[0:2,0:2] 

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)] 

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

like image 134
mgilson Avatar answered Oct 01 '22 12:10

mgilson