Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the shape of result array after slicing in Numpy

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?

like image 403
Kiran Avatar asked Sep 18 '15 08:09

Kiran


1 Answers

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]
like image 176
Anand S Kumar Avatar answered Sep 21 '22 15:09

Anand S Kumar