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?
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.
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.
You can slice a numpy array is a similar way to slicing a list - except you can do it in more than one dimension.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With