Skip to content
Advertisement

Part specification along different axes of numpy array

Why is arr[0:5][0:10] the same as arr[0:10][0:5] and what should I write if I want to get the array with shape (10,5)?

In the process of trying to crop a 2D numpy array I end up with the wrong dimensions. Ok, I figure, I just got my axes switched up, so I switch the order of the part specification.. and still get the same problem! I wrote this sanity check to make sure the problem wasn’t somewhere else in my code. For me, using Python 3.7 with numpy it finds the arrays have the same shape and prints “:(“. Here’s the function:

JavaScript

Advertisement

Answer

When you do arr[0:5], you take the first 5 items of the first dimension of arr (rows), then adding [0:10] you get the first 10 items, again on the first dimension (so only 5). The same is true with the reverse operation (arr[0:10][0:5]), you get the first 10 rows, then the first 5 rows of those 10 rows. In both cases, you never affect the second dimension!

What you want, to have shape (10, 5), is to slice both dimensions at once:

JavaScript

Example

input:

JavaScript

arr[0:5][0:10] or arr[0:10][0:5]:

JavaScript

arr[0:10, 0:5]:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement