I have difficult time understanding how the shape of resultant array be determined after slicing in numpy. For example I am using the following simple code:
import numpy as np
array=np.arange(27).reshape(3,3,3)
slice1 = array[:,1:2,1]
slice2= array[:,1,1]
print "Content in slice1 is ", slice1
print "Shape of slice1 is ", slice1.shape
print "Content in slice2 is ",slice2
print "Shape of Slice2 is", slice2.shape
Output of this is:
Content in slice1 is
[[ 4]
[13]
[22]]
Shape of slice1 is (3, 1)
Content in slice2 is [ 4 13 22]
Shape of Slice2 is (3,)
In both of these cases, content is same(as it should be). But they differ in shapes. So, how does the resultant shape is determined by numpy?
It basically boils down to this -
In [118]: a = np.array([1,2,3,4,5])
In [119]: a[1:2]
Out[119]: array([2])
In [120]: a[1]
Out[120]: 2
When you do a[1:2]
, you are asking for an array with 1 element.
When you do a[1]
you are asking for the element at that index.
Similar thing happens in your case.
When you do - array[:,1:2,1]
- it means all possible indexes from first dimension , a sub-list of indexes from second dimension (though the sub-list only contains one element) , and 1st index from third dimension. So you get back a array of arrays -
[[ 4]
[13]
[22]]
When you do - array[:,1,1]
- it means all possible indexes from first dimension, 1st index from second dimension, and 1st index from third dimension. So you get back an array -
[4 13 22]
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