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
[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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0